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

7 views (last 30 days)
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 Comments
Scott MacKenzie
Scott MacKenzie on 18 Oct 2021
Yes, I see now. I didn't realize that B was your example result. Just posted an answer.

Sign in to comment.

Answers (1)

Scott MacKenzie
Scott MacKenzie on 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

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by