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

 Réponse acceptée

Star Strider
Star Strider le 7 Août 2016
This works:
A = [5
2
2
4
3
2];
[Au,ia,ic] = unique(A, 'stable');
h = accumarray(ic, 1);
B = A;
B(ic~=Au(h==max(h))) = 0
B =
0
2
2
0
0
2

6 commentaires

Maryam Hamrahi
Maryam Hamrahi le 7 Août 2016
Thanks a lot for the help Star Strider.
It is really appreciated.
Star Strider
Star Strider le 7 Août 2016
As always, my pleasure.
Many thanks for your help Star Strider.
Why your code gives me error for the following matrix:
A =
5
0
0
4
3
0
your code gives me this:
B =
0
0
0
0
0
0
Thank you.
Star Strider
Star Strider le 7 Août 2016
It does that because zeros are the most frequent, and it sets the other elements to zero, producing a zero vector here. The impression I got from your original Question is that you wanted that result.
What result do you want from this vector?
Maryam Hamrahi
Maryam Hamrahi le 7 Août 2016
Sorry, it was my mistake. I have to correct it myself. I am thankful for your help.
Star Strider
Star Strider le 7 Août 2016
My pleasure.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by