How to store the output of a for loop in a matrix?

조회 수: 1 (최근 30일)
Morgan Roberts
Morgan Roberts 2017년 12월 8일
편집: Stephen23 2017년 12월 8일
Hi, I am trying to make a for loop which extracts data from one matrix using another matrix (extracting data from a when b = 1), which works fine but I am finding trouble when trying to store the output of the for loop in a matrix.
a = [3,4,5,2,1];
b = [1,1,4,3,1];
for i = 1:length(b)
if b(i) == 1
disp(a(i));
end
end
^^
This returns
3
4
1
However when I try and store the output in a matrix, it only stores the last iteration. How can I do this? Thanks, Morgan

채택된 답변

Stephen23
Stephen23 2017년 12월 8일
편집: Stephen23 2017년 12월 8일
Why waste time writing an loop as if MATLAB is an ugly low-level language like C++? Using logical indexing is simpler and very efficient:
>> a = [3,4,5,2,1];
>> b = [1,1,4,3,1];
>> c = a(b==1)
c =
3 4 1
If you really want to use a loop, then there are multiple possible ways to do it. Here is one:
>> V = find(b==1);
>> N = numel(V);
>> c = nan(1,N);
>> for k=1:N, c(k)=a(V(k)); end
>> c
c =
3 4 1
Also read this:

추가 답변 (0개)

카테고리

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