2013-05-25 121 views
0

我有一個數組,我想根據「索引數組」更改某些列中的值。更改矩陣中無循環的矩陣值

假設我有一個數組A,其中在列1和2的值是根據所述矩陣switch_mat進行切換,下面。

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 

是否有可能做到這一點沒有循環,使用一些像這樣的功能呢?

A(:,[1 2]) = renum(A(:,[1 2]),switch_mat) 

新的矩陣將是:

A(:,[1 2]) = 
1  2  
2  3 
2  4 
3  4 
4  5 
4  6 
5  6 

謝謝!

編輯: 在A矩陣開關將是:

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 

switch_mat = length(unique(A))

回答

2

尺寸這裏的一個可能的解決方案與arrayfun

A = arrayfun(@(x)switch_mat(switch_mat(:, 1) == x, 2), A); 

或者,也可以使用ismember

[tf, loc] = ismember(A, switch_mat(:, 1)); 
A(loc > 0) = switch_mat(loc(loc > 0), 2); 

我相信後一種方法應該更快。