Replacing some elements in the row with maximum value along the row

3 vues (au cours des 30 derniers jours)
Rajesh
Rajesh le 18 Oct 2021
Commenté : Rajesh le 18 Oct 2021
Hi,
I want to replace some elements of each rows in a matrix with the maximum value along the rows.
For example,
A=[1 2 3 0 0;7 4 5 1 0;2 4 6 0 3] to B=[1 2 3 3 3;7 4 5 1 7;2 4 6 6 3]
  3 commentaires
Rajesh
Rajesh le 18 Oct 2021
Hi, I have matrix with many rows and columns. I want to replace some elements from each row. That is I have lot of zeros in each rows. I want to replace the zeros with the maximum no present on the same rows. As I gave an example above, let's consider the following matrix A=[1 2 3 4 0 0;2 4 6 0 0 0;3 4 7 8 0 0] In this matrix maximum of row 1 is 4, maximum of row 2 is 6 similarly for row 3 it is 8. Now, I want the following matrix from A that is B=[1 2 3 4 4 4;2 4 6 6 6 6;3 4 7 8 8 8] Hope, it is clear now
Scott MacKenzie
Scott MacKenzie le 18 Oct 2021
Yes, I see now. I didn't realize that B was your example result. Just posted an answer.

Connectez-vous pour commenter.

Réponses (1)

Scott MacKenzie
Scott MacKenzie le 18 Oct 2021
There might be a simpler solution, but this seems to work:
A=[1 2 3 0 0; 7 4 5 1 0; 2 4 6 0 3]
A = 3×5
1 2 3 0 0 7 4 5 1 0 2 4 6 0 3
for i=1:size(A,1)
A(i,A(i,:)==0) = max(A(i,:));
end
B = A
B = 3×5
1 2 3 3 3 7 4 5 1 7 2 4 6 6 3

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by