How to store the output of a for loop in a matrix?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Morgan Roberts
am 8 Dez. 2017
Bearbeitet: Stephen23
am 8 Dez. 2017
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
0 Kommentare
Akzeptierte Antwort
Stephen23
am 8 Dez. 2017
Bearbeitet: Stephen23
am 8 Dez. 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:
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!