Question about Indexing a function
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Mashari Alharbi
le 27 Avr 2021
Commenté : Dyuman Joshi
le 28 Avr 2021
A = [-1 -2 0 1 2];
B = A(A<0);
What does A(A<0) mean exactly? and is there a way to do its function with an if statement? because I tried this and it did not work.
if A<0
B = A;
end
1 commentaire
Stephen23
le 27 Avr 2021
Modifié(e) : Stephen23
le 27 Avr 2021
"What does A(A<0) mean exactly?"
A(A<0)
^^^ logical index
^^ ^ indexing into A
Basic MATLAB concepts, like how to use indexing, are explained here:
"and is there a way to do its function with an if statement?"
It could be done with a bit of effort, but that would be a very poor use of MATLAB.
Réponse acceptée
Dyuman Joshi
le 27 Avr 2021
Modifié(e) : Dyuman Joshi
le 28 Avr 2021
B = A(A<0) means to allocate all the elements of A which are less than zero to B.
In case you want to use if statement to obtain the same, use a for loop as follows -
B=[];
for i=1:numel(A)
if A(i)<0
B = [B A(i)];
end
end
However, using B = A(A<0) should be opted.
2 commentaires
Plus de réponses (1)
Steven Lord
le 27 Avr 2021
That operation is logical indexing. Also see the "Indexing with Logical Values" section on this documentation page for more information.
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!