Reputation: 121
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. 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
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. Is there a faster way to do that?
Upvotes: 3
Views: 2996
Reputation: 12693
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
.
Example (changed initial values for clarity):
S = [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]; A = [5 3; 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
Upvotes: 3
Reputation: 32930
You could go about this with an arrayfun
one-liner, like this:
SS = arrayfun(@(x)A(2, (A(1, :) == x), S)
Upvotes: 1
Reputation: 523
If I have understood your question correctly, I would use numpy array instead of standard python arrays or lists. 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
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!). Anyways, the answer for MATLAB is very similar:
SS = zeros(size(S))
SS(S==A(1,1))=A(2,1)
SS(S==A(1,2))=A(2,2)
Upvotes: 1