Replacing n-d array elements based on pre-defined list
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
More Answers (1)
Roger Stafford
on 11 Jun 2013
Edited: Roger Stafford
on 11 Jun 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 Comments
Roger Stafford
on 11 Jun 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.)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!