How can I save data when it is being generated in a loop?

Hi, I am trying to generate a real time simulation of a sine wave and its derivative. The problem I am facing now is trying to save the data of the sine wave and its derivative while its being generated in the while loop to another file type, for exapmle Excel. So I am trying to save each iteration in excel while its running the data. I am really not sure if this possible or not to do so in Matlab.
You can find the code below. Please ask if you need any clearfication and any help is highly appriciated. Thank you in advance.
a = 5;
w = 0.2;
ts = 0.1;
t = -ts;
y = 1;
i = 1;
while t <= 40
t = t + ts;
y = a * sin(2*pi*w*t);
y1(i) = y;
T(i) = t;
if i == 1
b(i) = a*sin(2*pi*w*(t-ts));
x1 = (y1(i) - b(i))/ts;
else
x1 = ( y1(i) - y1(i - 1) )/ts;
end
x(i) = x1;
i = i + 1;
j = i - 1;
plot(T(1:j),y1(1:j),'b','linewidth',1);
hold on;
plot(T(1:j),x(1:j),'r','linewidth',1);
xlim([0 40]);
ylim([-7 7]);
grid on;
grid minor;
pause(0.01);
end

 Accepted Answer

you can check the xlswrite function and also the writetable function:
example:
a = 5;
w = 0.2;
ts = 0.1;
t = -ts;
y = 1;
i = 1;
while t <= 40
t = t + ts;
y = a * sin(2*pi*w*t);
y1(i) = y;
T(i) = t;
if i == 1
b(i) = a*sin(2*pi*w*(t-ts));
x1 = (y1(i) - b(i))/ts;
else
x1 = ( y1(i) - y1(i - 1) )/ts;
end
x(i) = x1;
i = i + 1;
j = i - 1;
plot(T(1:j),y1(1:j),'b','linewidth',1);
hold on;
plot(T(1:j),x(1:j),'r','linewidth',1);
xlim([0 40]);
ylim([-7 7]);
grid on;
grid minor;
pause(0.01);
end
varNames = {'T','y1','x'};
Ta = table(T',y1',x','VariableNames',varNames);
writetable(Ta,'yourfilename.xlsx')

3 Comments

JESUS DAVID ARIZA ROYETH Thank you very much for your answer. The code does save the data generated by the while loop only after it has finished with the loop. I was wondering if it is possible to save the data while it is still running and automatically exported ot excel?
It is also possible but it is more advisable to export them at the end since your program can be very slow, anyway it would be like this:
a = 5;
w = 0.2;
ts = 0.1;
t = -ts;
y = 1;
i = 1;
while t <= 40
t = t + ts;
y = a * sin(2*pi*w*t);
y1(i) = y;
T(i) = t;
if i == 1
b(i) = a*sin(2*pi*w*(t-ts));
x1 = (y1(i) - b(i))/ts;
else
x1 = ( y1(i) - y1(i - 1) )/ts;
end
x(i) = x1;
i = i + 1;
j = i - 1;
plot(T(1:j),y1(1:j),'b','linewidth',1);
hold on;
plot(T(1:j),x(1:j),'r','linewidth',1);
xlim([0 40]);
ylim([-7 7]);
grid on;
grid minor;
pause(0.01);
xlswrite('yourfilename2.xlsx',[T',y1',x'])
end
I understand it will be slower but it has to be done in this way in case similar simulation fails, I can get some data until the point where it failed. Thank you very much and your help is highly appriciated.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!