Borrar filtros
Borrar filtros

Replacing n-d array elements based on pre-defined list

1 visualización (últimos 30 días)
Pal
Pal el 11 de Jun. de 2013
Hi,
Suppose I have an n-d array of q unique integers. I want to replace the value of every element in this n-d array based on a list (q by 2 matrix) like this:
1 k
2 l
3 m
...,
which means that every element with value 1 in the n-d array is replaced by k, every element with value 2 is replaced by l, etc. k, l, m... are double-precision numbers.
What's the most efficient way of doing this? Obviously, one could loop through 1, 2, 3..., find their linear indices and set elements with those indices to k, l, m... I would like to do this faster, if possible.
Any ideas are appreciated.

Respuesta aceptada

Matt J
Matt J el 11 de Jun. de 2013
Editada: Matt J el 11 de Jun. de 2013
v=[k l m ...];
X=...%Your n-D array of integers
result = v(X);

Más respuestas (1)

Roger Stafford
Roger Stafford el 11 de Jun. de 2013
Editada: Roger Stafford el 11 de Jun. de 2013
If it isn't assumed that vector 'l' contains successive integers starting with 1, then you could do this:
[tf,loc] = ismember(V(:),l);
V(tf) = k(loc(tf));
where 'k' is the vector of values to replace those in 'l' and where 'V' is the n dimensional array. ('l' is the lowercase 'L', not the numeral.)
  2 comentarios
Pal
Pal el 11 de Jun. de 2013
Thanks. You mean l(:,1), the integer elements, I presume.
Roger Stafford
Roger Stafford el 11 de Jun. de 2013
My apologies. I misread your two vectors as being named 'l' and 'k'. My code still works whatever you name them provided they are the same length. It doesn't matter whether they contain integers or non-integers. Whenever an element in V is equal to one in 'l' (or whatever you call it,) it is replaced by the corresponding element in 'k' (or whatever you call that one.)

Iniciar sesión para comentar.

Categorías

Más información sobre Logical 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