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

1 次查看(过去 30 天)
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.

采纳的回答

Matt J
Matt J 2013-6-11
编辑:Matt J 2013-6-11
v=[k l m ...];
X=...%Your n-D array of integers
result = v(X);

更多回答(1 个)

Roger Stafford
Roger Stafford 2013-6-11
编辑:Roger Stafford 2013-6-11
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 个评论
Pal
Pal 2013-6-11
Thanks. You mean l(:,1), the integer elements, I presume.
Roger Stafford
Roger Stafford 2013-6-11
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.)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by