0

I want to find and replace numbers in a large matrix A. Vectors B and C have the same dimensions and contain values. Even though A may contain non-unique values, it has all the numbers of B. I want to search A for all values in B and replace them with the corresponding values in C.

For example, let A be a 2.5·106×4 matrix. B and C are 1.5·106×1 and have unique values. I've tried using the following for loop:

for q = 1:size(B, 1)
    A(A == B(q, 1)) = C(q, 1);
end

But it is very slow. Is there a faster way to do this?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Stoka
  • 39
  • 7
  • Show some example if u can. – Marcin Oct 28 '13 at 03:34
  • Isn't this just like [this problem](http://stackoverflow.com/questions/19597737/matlab-how-to-set-an-indexed-value-in-a-matrix-based-on-another-matrixs-values/19597917#19597917) where `B` and `C` here are the two columns of `B` in the other question? – chappjc Oct 28 '13 at 07:35

1 Answers1

5

The most straightforward solution that comes to mind is using ismember:

[tf, loc] = ismember(A, B);
A(tf) = C(loc(tf));
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • 1
    Seems right to me too. Note that `tf` is just `true(size(A))` and `loc` is the size of `A` so the answer is even simpler (`[~, loc] = ismember(A, B); A = C(loc);`). Although I suppose I am assuming all the values in `A` are in `B`, so perhaps a more general solution is better here. See [my answer from a couple days ago](http://stackoverflow.com/questions/19597737/matlab-how-to-set-an-indexed-value-in-a-matrix-based-on-another-matrixs-values/19597917#19597917) on the same problem with differently shaped data. – chappjc Oct 28 '13 at 07:45
  • 1
    Sorry, I was flipping things around. You need `tf` in this case. Good point. +1 – chappjc Oct 28 '13 at 08:01