Reputation: 25
Is there a function in Matlab to assign matrix elements by blocks? For example: Matrix A =
1 1 3 3 3 3 3 8 8 10
1 1 3 3 3 3 3 8 8 10
1 1 4 4 4 4 4 8 8 10
1 1 4 4 4 4 4 8 8 10
1 1 5 5 5 5 5 8 8 10
2 2 5 5 5 5 5 9 9 10
2 2 6 6 6 6 6 9 9 10
2 2 6 6 6 6 6 9 9 10
2 2 7 7 7 7 7 9 9 10
2 2 7 7 7 7 7 9 9 10
Matrix B=
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10
The user wants to create another matrix C where elements in the matrix B that correspond to 1 in the matrix A go to the matrix C (in the same position), similarly elements in the matrix B that correspond to 2 in the matrix A go to the matrix C (in the same position) and so on.
Upvotes: 0
Views: 122
Reputation: 1860
I t would very simple using Matlab operators (equality ==
in this case), and you don't need a function.
A == 1
would return all the indices of A (or B) that A is equal to 1 as a boolean matrix:
>> A == 1
ans =
1 1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Then B(A == 1)
will return all those true elements of the result above, in B (in a vector form):
>> B(A == 1)
ans =
1
2
3
4
5
1
2
3
4
5
So all you need is to equate C(A == n)
to B(A == n)
:
C = zeros(size(B)); % Create a matrix C with proper size
for k = 1:10
inds = A == k; % indices of A, B or C that correspond to A == k
C(inds) = B(inds);
end
Upvotes: 2
Reputation: 13876
Not sure if I understand correctly, but are you trying to do something like that?
C = zeros(size(A));
for k=1:10
C(B==k) = A(B==k); % or is it C(A==k) = B(A==k) ?
end
Upvotes: 0