storing variables after a loop (easy)

7 ビュー (過去 30 日間)
Paul Rogers
Paul Rogers 2021 年 1 月 8 日
コメント済み: Paul Rogers 2021 年 1 月 11 日
Hi, I managed to make a loop in wich I run a function.
The expected outputs are:
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
grid on
grid minor
xlabel('t [s]')
hold on
I'd like to call:
  8 件のコメント
Paul Rogers
Paul Rogers 2021 年 1 月 11 日
noope, post it a new answer, not as a comment to the first post, or i won't get the accept button


回答 (1 件)

Ryan Fedeli
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 ***
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
array_val is now a matrix, where each row is the data from the i'th iteration of the loop
I hope this helps
  1 件のコメント
Paul Rogers
Paul Rogers 2021 年 1 月 8 日
I am trying to follow your heads up, but in your case you know that a is going too have the same length a z, infacct I get a Subscripted assignment dimension mismatch.
In my case, I don't know how many points the ode is gooing to use for that step.



Help Center および File ExchangeThermal Analysis についてさらに検索




Community Treasure Hunt

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

Start Hunting!

Translated by