Indexing multidimensional matrices using logical arrays

I want to efficiently find number in a multidimensional array that fall into
some category and do something to them,like in the code below:
nc=4;
mc=1000;
r1=normrnd(0,1,[nc,mc,n-1]);
for j=2:n
indexNeg(:,:)=r1(:,:,j)<0.5;
r1(:,:,j)=-r1(indexNeg,j);
end
here, I create a multidimensional array of random numbers and change sign of any number smaller than 0.5
I am getting this error Subscript indices must either be real positive integers or logicals.
How to properly use the logical index?

 Respuesta aceptada

A statement like TF = A < 0.5 produces a logical array TF that has the same size as A. You can directly use TF to index into A. An example
A = rand(3,2,4)
TF = A < 0.5 ;
size(A)
size(TF)
A(TF) = -A(TF)
The number of dimensions of A is not affecting this at all.

Más respuestas (2)

Andrei Bobrov
Andrei Bobrov el 17 de Dic. de 2013
Editada: Andrei Bobrov el 17 de Dic. de 2013
l = r1 < .5;
r1(l) = -r1(l);
On comment by Marco
r1 = abs(r1);

2 comentarios

Marco Pereira
Marco Pereira el 17 de Dic. de 2013
Editada: Marco Pereira el 17 de Dic. de 2013
In analogy to your answer
nc=4;
mc=1000;
n=100;
r1=normrnd(0,1,[nc,mc,n-1]);
l=r1(:,:,2)<0;
If I print r1(l) here, not all numbers are negative so the next line wouldn't do what I want done.
r1(l)=-r1(l);
What you want?

Iniciar sesión para comentar.

Marco Pereira
Marco Pereira el 17 de Dic. de 2013
the problem is that I am looping through one of the dimensions and making the comparison.
l=r1(:,:,2)<0;
In this line I am comparing only the column where k=2 (in an r1(i,j,k) array). I could always to a loop but that would be inefficient.
This makes that the logical array to be one dimension smaller than the original array. The logical array needs to be concatenated with the integer corresponding to the missing dimension.
I am trying to learn best practices (the vectorized solution to a multidimensional array comparison problem) where the comparison is done is a section of the array at a time.

Categorías

Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.

Preguntada:

el 17 de Dic. de 2013

Respondida:

el 17 de Dic. de 2013

Community Treasure Hunt

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

Start Hunting!

Translated by