How to save values changing in a loop without overwriting?
3 views (last 30 days)
Show older comments
I need every 100th value for
emag
to be saved against the corresponding value of t so that I can plot the results, however I have tried
dlmwrite('filename.txt', emag,'-append', '\t')
dlmwrite('filename.txt', t,'-append', '\t')
and it's not working for me and I'm not very well versed with MATLAB at all so any help would be very greatly appreciated. This is my loop;
m = 0;
for i = 1: m
m = m + 1;
if m == 100
C{i} = emag;
C2{i} = t;
E(i,1) = emag;
E(i,2) = t;
%m = 0;
t = t + steps*delta;
end
end
5 Comments
Rik
on 30 Apr 2021
The loop isn't, the code before it is.
%generate values to avoid errors
P=rand(2,20);V=rand(2,20);G=rand;M=rand;H=rand;t=rand;
D=dot(P(2,:), V(2,:))
e1=norm(V(2,:));
e1=e1^2
mu=G*M(1)
e2=e1/mu
r1=norm(P(2,:))
e3=e2/r1
e4=e3*P(2,:)
e5=D/mu
e6=e5*V(2,:)
e=e4-e6
emag=norm(e)
emag=emag/1.0e+10
%t = t + steps*delta;
steps = 100;
delta = 0.5;
update_plot(P,H,t)
m = 0;
for i = 1: m
m = m + 1;
if m == 100
C{i} = emag;
C2{i} = t;
E(i,1) = emag;
E(i,2) = t;
matrixToWrite = [t emag];
writematrix(matrixToWrite, 'myData.txt')
%m = 0;
t = t + steps*delta;
end
end
function update_plot(P,H,t)
end
Answers (1)
Nagasai Bharat
on 3 May 2021
Hi,
From my understanding you are trying to loop over and save every 100th element corresponding to 100th element is t.
The problem arising in the initialization of the for loop . In you code, the statements inside the loop are not excecuted due to incorrect use of for.
for i = a:b
Here while indexing an array i has to be an whole number and also b should be greater than a for the looping. There variables a and b should be already defined and not be changed. Other alternatives to use is the while loop as there a logical condition would be checked to loop further.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!