Reputation: 14939
I have an array where I want to change the values in certain columns according to an "indexing-array".
Suppose I have an array A
, where the values in column 1 and 2 are to be switched according to the matrix switch_mat
, below.
A(:,[1 2]) =
1 2
2 6
2 7
6 7
7 12
7 13
12 13
switch_mat =
1 1
2 2
6 3
7 4
12 5
13 6
Is it possible to do this without loops, using some functions like this?
A(:,[1 2]) = renum(A(:,[1 2]),switch_mat)
The new A matrix will be:
A(:,[1 2]) =
1 2
2 3
2 4
3 4
4 5
4 6
5 6
Thanks!
EDIT: The switch in the A matrix will be:
1 -> 1
2 -> 2
6 -> 3
7 -> 4
12 -> 5
13 -> 6 % 13 becomes a 6, because they are in the same row of switch_mat
The dimension of switch_mat = length(unique(A))
Upvotes: 0
Views: 724
Reputation: 32930
Here's a possible solution with arrayfun
:
A = arrayfun(@(x)switch_mat(switch_mat(:, 1) == x, 2), A);
Alternatively, you can use ismember
:
[tf, loc] = ismember(A, switch_mat(:, 1));
A(loc > 0) = switch_mat(loc(loc > 0), 2);
I believe the latter method should be faster.
Upvotes: 2