How can I save date that is overwritten on each loop?

1 Ansicht (letzte 30 Tage)
Ailun Yang
Ailun Yang am 30 Okt. 2020
Kommentiert: Star Strider am 30 Okt. 2020
I have written a code which performs Eulers method on a vector of h'd and a for loop is used. My problem is that the data is overwritten each time because I didn't think I would need to save it for later use. Then I was assigned to created a table out of each set of h's and y outputs. I created the table in the loop but the data is overwriten each time. How can I save the data in the loop and is this the best way to write the code? This was a school assigment but I have already turned it in and I'm just trying to have a better understanding of Matlab.
Q = 500; %given
A = 1300; %given
a = 150; %given
h = [1 .5 .1 .005]; %given delta t
f = @(t,y)(3.*(Q./A).*(sin(t)).^2)-((a.*(1+y).^1.5)./A); %diff eq -- the for loop will plug the multipe values back into this equation.
t_init = 0;
t_final = 10
for i = 1:length(h)
t = t_init:h(i):t_final; %this for loop will count and identify the multiple h, y, t values
dt = length(t);
y = zeros(1,dt);
y(1)=1; %inital condidition of y
for j = 2:dt
y(j) = y(j-1)+h(i)*f(t(j-1),y(j-1)); %eulers
end
plot(t,y); %after the values have been calculated the loop then plots the vectors
hold on;
T = table(t',y','VariableNames',["Delta T","Delta Y"]) %created the table DURING EACH LOOP **The data is not stored in a variable but is overwritten on each loop**
save('Data.mat','T'); % me trying to save the data on each h but failing
end
title('y(i)-water levels vs delta t')
ylabel('Water levels')
xlabel('Time')
legend('t1 = 1', 't2 = .5','t3 = .1','t4 = .05')

Antworten (2)

Cris LaPierre
Cris LaPierre am 30 Okt. 2020
Create your mat file name dynamically.
save(['Data' num2str(i) '.mat'],'T'); % me trying to save the data on each h but failing

Star Strider
Star Strider am 30 Okt. 2020
I would record the individual table objects in a cell array, then save them after the loop, if desired:
T{i,:} = table(t',y','VariableNames',["Delta T","Delta Y"])
then, somewhere after the loop:
save('Data.mat','T')
I tested that and it ran without error. I also checked to be certain it also loads correctly:
T2 = load('Data.mat');
T = T2.T
It does.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by