# How can I save the output in a loop to an external text file?

12 views (last 30 days)
Lauren Miller on 29 Apr 2021
In my loop, I'm trying to save the outputted values of eccentricity to a text file so that I can use this to plot the answers for my results but it's just not working and I have no clue where I'm going wrong.
I don't want to save every value that comes out because there'll be a lot, I just want to save 1 value for every 100 so I've set up a for loop but I'm not very experienced with MATLAB so I think it's ended up a bit of a mess. Any help would be incredibly appreciated
The loop:
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)
for i = 1: n
m = 0;
m = m + 1;
if m == 100
C{i} = emag;
C2{i} = t;
E(i,1) = emag;
E(i,2) = t;
dlmwrite('local filename.txt',emag,'-append', '\t')
dlmwrite('local filename.txt',t,'-append', '\t')
%m = 0;
t = t + steps*delta;
end
end

Benjamin Großmann on 29 Apr 2021
Edited: Benjamin Großmann on 29 Apr 2021
There are a few problems inside your loop. In each step you set m equal to zero and increment it to one. So m is not growing as it is intended to be. m=0 should be prior to the beginning of the loop. Furthermore, inside the loop you are using dlmwrite to write emag and t to text files, but emag is not changing inside the loop.
Basically, you are not writing anything because m never reaches 100. If you change this and m reaches 100, 200, ... then you are appending the same emag to the file.
Howerer, if you have some data in the variable myData, you can write every 100th value to a text file as follows:
% Generate some random data
myData = rand(1e6,1);
% write every 100th data point
writematrix(myData(1:100:end), 'myData.txt')
Edit: If you want to save the variable for further processing in matlab, than I would recommend to save the variable as mat-File instead of a text file. Mat-Files are compressed, a lot faster to write and read and I think you do not neccesseraly need to downsample your data. The one-liner
save('myMatFile', 'myData')
does the job. Be careful, that your variable names appear in appostrophes, i.e. as char array.
Benjamin Großmann on 30 Apr 2021
I have seen your other questions regarding the same problem... Please do not use the for loop to save every 100th element. You can achive this with an one-liner:
matrixToWrite = [t(1:100:end) emag(1:100:end)];
writematrix(matrixToWrite, 'myData.txt', 'WriteMode', 'append') % Default write mode is 'overwrite'