How to turn multiple outputs into a array

조회 수: 19 (최근 30일)
zephyr21
zephyr21 2016년 6월 21일
편집: Kiran Ramsaroop 2019년 4월 30일
I have N=60
for n=1:N
Rate2Graph=Rate_overtime(5,5,n);
end
This gives an answer for each time step. How can I take all those answers and put them into an array?

답변 (2개)

James Tursa
James Tursa 2016년 6월 22일
편집: James Tursa 2016년 6월 22일
Assuming Rate_overtime is a function that outputs a double scalar, you could do this:
Rate2Graph = zeros(1,N);
for n=1:N
Rate2Graph(n) = Rate_overtime(5,5,n);
end
If Rate_overtime is simply a 3D array, then you could do the above, or you could do this:
Rate2Graph = squeeze(Rate_overtime(5,5,1:N));

Kiran Ramsaroop
Kiran Ramsaroop 2019년 4월 30일
편집: Kiran Ramsaroop 2019년 4월 30일
Following on from this, I tend to do away with the loop by using a cell2mat, i.e.
Rate2Graph = cell2mat({Rate_overtime(5,5,1:N)});
This notation is particularly helpful when you have an array or structure that you wish to dig into and you do not want to loop over every value in turn.
For example, given the 1xN NormalDistribution array, P, one may wish to pull out the mean value from each N:
P(1:N).mu would give N results
{P(1:N).mu} wraps everything into a cell array
using a cell2mat then returns the values in a single array:
cell2mat({P(1:N).mu})

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by