2

Say I have a matrix A

A =
 0     1     2
 2     1     1
 3     1     2

and another matrix B

B =
 0    42
 1    24
 2    32
 3    12

I want to replace each value in A by the one associated to it in B.

I would obtain

A =
 42     24     32
 32     24     24
 12     24     32

How can I do that without loops?

chappjc
  • 30,359
  • 6
  • 75
  • 132
mooviies
  • 45
  • 5

2 Answers2

6

There are several ways to accomplish this, but here is an short one:

[~,ind]=ismember(A,B(:,1));
Anew = reshape(B(ind,2),size(A))

If you can assume that the first column of B is always 0:size(B,1)-1, then it is easier, becoming just reshape(B(A+1,2),size(A)).

chappjc
  • 30,359
  • 6
  • 75
  • 132
1
arrayfun(@(x)(B(find((x)==B(:,1)),2)),A)
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • 2
    `arrayfun` is an easy way to express a `for` loop in one line, but keep in mind that [`arrayfun` performance is not usually what you would expect](http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why). Still, +1 for conciseness! – chappjc Oct 25 '13 at 19:29
  • @chappjc: Thx, bookmarked. Never noticed arrayfun could be that slow. – Daniel Oct 25 '13 at 19:41