Rewrite for loop with find function

6 visualizzazioni (ultimi 30 giorni)
Johnathan Pryor
Johnathan Pryor il 18 Nov 2019
Commentato: Vladimir Sovkov il 19 Nov 2019
The question:
  1. See the following code. Rewrite the code in one line using the find function.
x=[-1 3 7 2 4 0];
v=[];
for i=1:length(x)
ifx(i)<=2
v=[v, x(i)];
end
end
I have tried x=[-1 3 7 2 4 0]; find(x<=2)
which returns 1 4 6. What I need it to display is -1 2 0
How would I do this? thanks!

Risposte (1)

Erivelton Gualter
Erivelton Gualter il 18 Nov 2019
The function find returns the indeces according to the condition. So, in order to diplay the values, you might use the following:
x(find(x<=2))
Here is more information.
  4 Commenti
Erivelton Gualter
Erivelton Gualter il 18 Nov 2019
Modificato: Erivelton Gualter il 19 Nov 2019
I fixed the link. It is just the find document. Glad it worked.
If it was helpful, please accept the answer.
Vladimir Sovkov
Vladimir Sovkov il 19 Nov 2019
"find" is redundant here. You can just use
x(x<=2);

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by