logical arry indexing: how to extract columns that match a criterion

10 visualizaciones (últimos 30 días)
I want to extract columns from a 2D array, when the element in row 3 of the column matches a criterion. Example:
>> rng(42); a=rand(3,5); disp(a)
0.3745 0.5987 0.0581 0.7081 0.8324
0.9507 0.1560 0.8662 0.0206 0.2123
0.7320 0.1560 0.6011 0.9699 0.1818
I want to pick out the columns of a for which the row 3 element is between 0.6 and 0.8. In this example, that means I want an array with columns 1 and 3 of a, since those columns meet the row 3 criterion. The following for loop does the job, but it seems inelegant.
>> j2=1;
for j1=1:5
if a(3,j1)>.6 && a(3,j1)<.8
b(:,j2)=a(:,j1);
j2=j2+1;
end
end
disp(b)
0.3745 0.0581
0.9507 0.8662
0.7320 0.6011
Here are some failed attempts to do it with logical indexing.
>> b=a(a(4,:)>.6 && a(4,:)<.8); disp(b)
Index in position 1 exceeds array bounds (must not exceed 3).
>> b=a(a(4,:)>.6 && a(4,:)<.8,:); disp(b)
Index in position 1 exceeds array bounds (must not exceed 3).
>> b=(a(4,:)>.6 && a(4,:)<.8,:); disp(b)
Error: Invalid expression.
>> tf=a>.6 & a<.8;
>> b=a(tf(4,:)); disp(b)
Index in position 1 exceeds array bounds (must not exceed 3).
Thank you for your assistance.

Respuesta aceptada

David Hill
David Hill el 22 de Feb. de 2021
b=a(3,:);%whatever row
c=a(:,b>=.6&b<=.8);
  1 comentario
William Rose
William Rose el 23 de Feb. de 2021
Thank you David.
The right answer always looks obvious in retrospect.
This site and the people on it are great!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by