Clear Filters
Clear Filters

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

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 8 Dec 2017
Edited: Stephen23 on 8 Dec 2017
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:

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!