Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Pal
Pal le 11 Juin 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.

Réponse acceptée

Matt J
Matt J le 11 Juin 2013
Modifié(e) : Matt J le 11 Juin 2013
v=[k l m ...];
X=...%Your n-D array of integers
result = v(X);

Plus de réponses (1)

Roger Stafford
Roger Stafford le 11 Juin 2013
Modifié(e) : Roger Stafford le 11 Juin 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 commentaires
Pal
Pal le 11 Juin 2013
Thanks. You mean l(:,1), the integer elements, I presume.
Roger Stafford
Roger Stafford le 11 Juin 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.)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by