Replacing n-d array elements based on pre-defined list
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
Roger Stafford
am 11 Jun. 2013
Bearbeitet: Roger Stafford
am 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 Kommentare
Roger Stafford
am 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.)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!