Comparing more than two columns of a matrix using '<' or '>' symbol

How to compare more than two columns of a matrix using '<' or '>' symbol?
For example, if I have a matrix A and if I compare the columns using '<' symbol
A=
2 5 4
4 1 2
6 0 1
7 5 8
I should get the output as
1 0 0
0 1 0
0 1 0
0 1 0
So, is there any solution that doesn't restrict for any two columns or three columns but in general more than two columns

 採用された回答

Guillaume
Guillaume 2015 年 10 月 26 日

0 投票

There is only ever one number per row that is smaller than all the other columns, and that is the minimum of the row. Hence, use min:
A = [2 5 4; 4 1 2; 6 0 1; 7 5 8];
[~, col] = min(A, [], 2);
B = zeros(size(A));
B(sub2ind(size(A), 1:size(A, 1), col')) = 1

1 件のコメント

pavikirthi
pavikirthi 2015 年 10 月 26 日
Thanks, it absolutely works fine for any number of columns.

サインインしてコメントする。

その他の回答 (3 件)

Steven Lord
Steven Lord 2015 年 10 月 26 日

1 投票

Take a look at the second output of the MIN function.
A = [2 5 4; 4 1 2; 6 0 1; 7 5 8];
[~, index] = min(A, [], 2)
Then use either a FOR loop or SUB2IND to fill in the appropriate elements in your output matrix.

1 件のコメント

Stephen23
Stephen23 2015 年 10 月 26 日
>> A = [2 5 4; 4 1 2; 6 0 1; 7 5 8];
>> [~,idx] = min(A,[],2);
>> X = false(size(A));
>> X(sub2ind(size(A),1:size(A,1),idx.')) = true
X =
1 0 0
0 1 0
0 1 0
0 1 0

サインインしてコメントする。

Lessmann
Lessmann 2015 年 10 月 26 日

0 投票

Hi,
you can achieve this by using
B = diff(-A,1,2) < 0
You have to concatenate a column of zeros, so that A and B are of equal size.

1 件のコメント

Thorsten
Thorsten 2015 年 10 月 26 日
That's only valid if you want to restrict your comparison to adjacent columns. In the example, column 1 is not compared to 3.

サインインしてコメントする。

Thorsten
Thorsten 2015 年 10 月 26 日

0 投票

A = [2 5 4
4 1 2
6 0 1
7 5 8];
pairs = nchoosek(1:size(A,2), 2)
X = cell2mat(arrayfun(@(i)( A(:, pairs(i,1)) < A(:,pairs(i,2))), 1:3, ...
'UniformOutput', false))

1 件のコメント

pavikirthi
pavikirthi 2015 年 10 月 26 日
Thanks. But, I want to compare whether column 1 elements are '<' column 2 and column 3 and similarly column 2 elements are '<' column 1 and column 3 and lastly column 3 elements are '<' column 1 and column 2.
I want to perform this operation in general with any number of columns. So, for this example of 3 column matrix I should get the output as
1 0 0
0 1 0
0 1 0
0 1 0

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

タグ

質問済み:

2015 年 10 月 26 日

コメント済み:

2015 年 10 月 26 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by