Find rows with maximum number and replace them with 1

I have a matrix with n rows and 1 column. I would like to find row which have the maximum number. Then, replace 1 in these rows and replace 0 in other rows.
For instance: I have matrix A and I would like to produce matrix B.
A=
5
0
0
4
3
0
B=
0
1
1
0
0
1

 採用された回答

Stephen23
Stephen23 2016 年 8 月 8 日
編集済み: Stephen23 2016 年 8 月 8 日

1 投票

A = [5;0;0;4;3;0];
[cnt,idx] = histc(A,unique(A));
[~,idz] = max(cnt);
B = idx==idz;
outputs this
>> B
B =
0
1
1
0
0
1
and A = [1;1;0;4;3;1]; outputs this:
>> B
B =
1
1
0
0
0
1

1 件のコメント

Maryam Hamrahi
Maryam Hamrahi 2016 年 8 月 8 日
Thank you very much Stephen Cobeldick.nYour cooperation is really appreciated.
Also Thanks a lot José-Luis and Walter Roberson.

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 8 月 8 日

1 投票

B = A == min(A);

4 件のコメント

Maryam Hamrahi
Maryam Hamrahi 2016 年 8 月 8 日
編集済み: Maryam Hamrahi 2016 年 8 月 8 日
Many thanks Walter Roberson .
Your code does not work for me when I have the following matrix:
A=
1
1
0
4
3
1
the answer should be like this:
B=
1
1
0
0
0
1
Walter Roberson
Walter Roberson 2016 年 8 月 8 日
In your first example you want a 1 where each original value was 0, which was the smallest value in the matrix. In the second example, you do not want a 1 where each original value was 0, even though 0 is the smallest value in the matrix. Your examples are inconsistent with each other.
Also your original version talked about maximum but you wanted the 1 where the minimum was, so your examples are not consistent with the description either.
Maryam Hamrahi
Maryam Hamrahi 2016 年 8 月 8 日
編集済み: Maryam Hamrahi 2016 年 8 月 8 日
Many thanks Walter Roberson.
I am not looking for the min. or max. values in the matrix.
I want to find rows which has the most frequent number. for instance in example 2, rows with number "1" are repeated three times. Therefore, I want to replace these rows with "1". However, in this example the numbers are already 1. Afterward, I want to replace 0 in other rows.
Thank you for the cooperation.
Maryam Hamrahi
Maryam Hamrahi 2016 年 8 月 8 日
Please also look at my comment for José-Luis.
Thanks a lot.

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

José-Luis
José-Luis 2016 年 8 月 8 日
編集済み: José-Luis 2016 年 8 月 8 日

1 投票

What you ask and the example you show are not consistent. To produce what you show:
B = A == 0

1 件のコメント

Maryam Hamrahi
Maryam Hamrahi 2016 年 8 月 8 日
Many thanks José-Luis. Please see my comment for Walter Roberson.
If you look at the following example, 2 is the most frequent number in the matrix, so, I want to replace this number with 1. Afterward, I want to replace 0 in the other rows.
A=
2
2
0
4
3
2
B=
1
1
0
0
0
1

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

カテゴリ

ヘルプ センター および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by