Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Morgan Roberts
Morgan Roberts le 8 Déc 2017
Modifié(e) : Stephen23 le 8 Déc 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

Réponse acceptée

Stephen23
Stephen23 le 8 Déc 2017
Modifié(e) : Stephen23 le 8 Déc 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:

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by