storing variables after a loop (easy)
7 ビュー (過去 30 日間)
表示 古いコメント
Hi, I managed to make a loop in wich I run a function.
The expected outputs are:
t,y(:,1),y(:,2)
The problem is that at the end of the iteration I only get the last part of the loop, but
I would llike to have all the datas, for those vectors, computed during the looop.
Here's the part of the code:
for i=1:(length(giri)-2)
U1(i) = (D1*pi.*giri(i))/60;
U2(i) = (D2*pi.*giri(i))/60;
B(i) = U1(i)./(2.*wh.*Lc);
[t,y]=ode113(@greitzer,[t0(i),tf(i)],[y1(i),y2(i)],options,U1(i),U2(i),B(i)); %I found ode113 is way more efficient
t0(i+1) = time_rpm(i+1); %simulation's start [s]
tf(i+1) = time_rpm(i+2); %simulation's finish [s]
y1(i+1) = y(end,1); %initial condition 1
y2(i+1) = y(end,2); %initial condition 2
plot(t,y(:,2))
grid on
grid minor
xlabel('t [s]')
ylabel('\Psi')
hold on
end
I'd like to call:
t=time
y(:,1)=phi
y(:,2)=psi
回答 (1 件)
Ryan Fedeli
2021 年 1 月 8 日
This example is simplified, but to save a value from each loop iteration, all you need to do is save it into an array. The lines with asterisks are the important parts:
z = linspace(1,50,10); % arbitrary vector
b = z; % arbitrary values for example function
array_val = zeros(1,length(z)); % preallocate array for loop speed ***
for i = 1:length(z)
a = b(i)*1.1; % example function to create data
array_val(i) = a; % save the value from this iteration into an array ***
end
disp(array_val)
But if "a" in this example is not a single value, but an array itself, you'd need to save it into a matrix. In this case, it would look something like:
array_val = zeros(length(z)); % 1) preallocate *matrix* of zeros, length(z) by length(z) in size.
% 2) you'll need to figure out what these dimensions should be.
% 3) This line is helpful so the loop runs faster, but it's not necessary
for i = 1:length(z)
a = b(i).*z; % example function to create a row vector of data (array of data)
array_val(:,i) = a; % save the data in the row vector into the matrix in the i'th position
end
disp(array_val)
array_val is now a matrix, where each row is the data from the i'th iteration of the loop
I hope this helps
参考
カテゴリ
Help Center および File Exchange で Thermal Analysis についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!