I'm trying to create a classes matrix in MATLAB preferably without using for loops. So I have A:
A = [ 1 2 3 4;
2 5 4 1;
7 2 3 4];
Now I want to create a classes matrix so I want to look for the max value of each column and whatever that position is will become a "1". So using A, I want B to look like this:
B = [ 0 0 0 1;
0 1 0 0;
1 0 0 0];
I've been trying to use the following code to create the B matrix and then search for the max value in each column using the following code:
[rows_A columns_A] = size(A);
B = zeros(rows_A, columns_A);
max(A, [], 2);
Then I'm trying to use ind2sub to get the position within A so I can put a "1" in the B matrix. This approach isn't working out. The matrix A can be of any dimensions. Any help is greatly appreciated.
You can use max and sub2ind to flag the column with the largest value for each row as follows:
[~,indMaxCol] = max(A,[],2);
B = zeros(size(A));
B(sub2ind(size(B),1:size(B,1),indMaxCol.')) = 1 %' flag largest column, each row
B =
0 0 0 1
0 1 0 0
1 0 0 0
Another solution, which does not require sub2ind is to create a sparse matrix:
Bs = sparse(1:size(B,1),indMaxCol,1)
Bs =
(3,1) 1
(2,2) 1
(1,4) 1
This can be converted to a full matrix with full(Bs).
One-line solution with bsxfun (compute the maximum for each row and then compare for equality):
bsxfun(@eq, A, max(A,[],2))
This differs from @chappjc's solution in one aspect: if the maximum is achieved more than once in some row, this gives all columns where the maximum is attained. For example:
>> A = [ 4 2 3 4
2 5 4 1
7 2 3 4 ];
>> bsxfun(@eq, A, max(A,[],2))
ans =
1 0 0 1
0 1 0 0
1 0 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With