Storing data from a triple for loop in a matrix
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello! Can someone help me with the following quation?
I want to make a matrix with outputs of a triple for loop. The code is as follows.
First there is a odefunction that is used in the script.
The the script with the function handle:
for i = 1:3 % The for loops runs 27 times because there are 3^3 options.
for j = 1:3
for k = 1:3
odefunc = @(t,y) odeFunction(t,y,Cint, Cwall, R1(i), R2(j), Rwin(k))
% integrate the system of differential equations from tspan(1) to
% tspan(2) with initial conditions y0
[t,y] = ode45(odefunc, tspan, y0);
end
This computes different outputs with 27 possible input options. I want to store these outputs in matrix of
K = zeros(27, 1440);
댓글 수: 0
채택된 답변
Star Strider
2021년 10월 29일
Store the intermediate results in cell arrays, and sort the results out later —
for i = 1:3 % The for loops runs 27 times because there are 3^3 options.
for j = 1:3
for k = 1:3
odefunc = @(t,y) odeFunction(t,y,Cint, Cwall, R1(i), R2(j), Rwin(k))
% integrate the system of differential equations from tspan(1) to
% tspan(2) with initial conditions y0
[t,y] = ode45(odefunc, tspan, y0);
tc{i,j,k} = t;
yc{i,j,k} = y;
end
end
end
If ‘Cwall’ has more than 2 elements, all the ‘t’ vectors and ‘y’ matrices will have the same row dimension, however it is still easier to save (and later address) the results as cell arrays rather than as concatenated matrices.
.
댓글 수: 4
Star Strider
2021년 10월 29일
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.
추가 답변 (1개)
Jon
2021년 10월 29일
편집: Jon
2021년 10월 29일
It isn't completely clear from your description, but assuming the output you want to save is the vector y from each diff eq solution, and that this always has 1440 elements, you could do this:
K = zeros(27,1440); % preallocate
count = 0;
for i = 1:3
for j = 1:3
for k = 1:3
% increment loop counter
count = count + 1
.
.
.
[t,y] = ode45(odefunc, tspan, y0);
K(count,:) = y(:)'; % use y(:)' to make sure it is a row
end
end
end
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!