フィルターのクリア

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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by