[英]replace indices in matrix with other values in matlab
Suppose now I have a matrix 假设我现在有一个矩阵
S = [1 1 1 2 2 2;
1 1 1 2 2 2;
2 2 2 2 1 1;
2 2 2 2 1 1;
2 2 2 2 1 1]
And another matrix 另一个矩阵
A = [1 2;
2 4]
The first row in A is the unique indices of S, and the second row contains the values that the values in the first row will be replaced. A中的第一行是S的唯一索引,第二行包含第一行中的值将被替换的值。 That is, all "1"s in S will be replaced by 2, and all "2"s will be replaced by 4. Finally I'll get a matrix
也就是说,S中的所有“1”将被2替换,所有“2”将被4替换。最后我将获得一个矩阵
SS = [2 2 2 4 4 4;
2 2 2 4 4 4;
4 4 4 4 2 2;
4 4 4 4 2 2;
4 4 4 4 2 2]
Right now what I'm doing is: 现在我正在做的是:
SS = zeros(size(S));
for i = 1:size(A,2)
SS(S==index(A(1, i)) = A(2,i);
end
Now, I have a pretty big matrix, and using a for loop is a little bit slow. 现在,我有一个非常大的矩阵,使用for循环有点慢。 Is there a faster way to do that?
有更快的方法吗?
Use the second output of ismember
to give you indices of the values in row 1 of A. Use these indices to directly create matrix SS
. 使用
ismember
的第二个输出为您提供A的第1行中的值的索引。使用这些索引直接创建矩阵SS
。
Example (changed initial values for clarity): 示例(为清晰起见,更改了初始值):
S = [5 5 5 3 3 3;
S = [5 5 5 3 3 3; 5 5 5 3 3 3;
5 5 5 3 3 3; 3 3 3 3 5 5;
3 3 3 3 5 5; 3 3 3 3 5 5;
3 3 3 3 5 5; 3 3 3 3 5 5];
3 3 3 3 5 5]; A = [5 3;
A = [5 3; 2 4];
2 4];
>> [~, Locb] = ismember(S,A(1,:))
Locb =
1 1 1 2 2 2
1 1 1 2 2 2
2 2 2 2 1 1
2 2 2 2 1 1
2 2 2 2 1 1
>> SS = reshape(A(2,Locb),size(S))
SS =
2 2 2 4 4 4
2 2 2 4 4 4
4 4 4 4 2 2
4 4 4 4 2 2
4 4 4 4 2 2
If I have understood your question correctly, I would use numpy array instead of standard python arrays or lists. 如果我正确理解了你的问题,我会使用numpy数组而不是标准的python数组或列表。 Then the code becomes very simple as shown below:
然后代码变得非常简单,如下所示:
# Import numpy
from numpy import array, zeros, shape
# Create the array S
S = array([[1,1,1,2,2,2],[1,1,1,2,2,2],[2,2,2,2,1,1],[2,2,2,2,1,1],[2,2,2,2,1,1]])
# Create the array A
A = array([[1,2],[2,4]])
# Create the empty array SS
SS = zeros((shape(S)))
# Actual operation needed
SS[S==A[0,0]]=A[1,0]
SS[S==A[0,1]]=A[1,1]
Now if you see the array SS, it will look as follows: 现在,如果您看到数组SS,它将如下所示:
SS
array([[ 2., 2., 2., 4., 4., 4.],
[ 2., 2., 2., 4., 4., 4.],
[ 4., 4., 4., 4., 2., 2.],
[ 4., 4., 4., 4., 2., 2.],
[ 4., 4., 4., 4., 2., 2.]])
Sorry for the confusion earlier. 对不起之前的混乱。 I had (for some reason) assumed that this question was for Python (my bad!).
我(由于某种原因)认为这个问题是针对Python的(我的坏!)。 Anyways, the answer for MATLAB is very similar:
无论如何,MATLAB的答案非常相似:
SS = zeros(size(S))
SS(S==A(1,1))=A(2,1)
SS(S==A(1,2))=A(2,2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.