If loop issue for assigning new variable

Hello everyone,
I got an incomprehensible issue. In the code below, I want to make a new matrix with maximum on each row but keep remain the same index as the original matrix. However, when <j> runs, I cannot assign its value to variable <mark>. The value of <mark> is unchangable, it still remains 1.
Please help me, I don't understand what happening.
Thank you in advance.
close all; clc; clear
[x,y] = meshgrid(-2:2,-2:2)
[xlength,ylength] = size(x);
r = zeros(xlength,ylength)
s = zeros(xlength,ylength)
Pnpos = zeros(xlength,ylength)
Pnpo = 3*x.*x.*y - x.*y + 2*y + x - 7
maxRow = 0;
for i = 1:xlength
maxRow = max(Pnpo(i,:))
mark = 1;
for j = 1:ylength
if maxRow < Pnpo(i,j)
maxRow = Pnpo(i,j);
mark = j
end
end
Pnpos(i,mark) = maxRow;
end

5 Comments

maxRow = max(Pnpo(i,:))
OK it starts as the largest value in the row
if maxRow < Pnpo(i,j)
maxRow is the largest value in the row. It cannot be less than any element in the row, only equal to one or more copies of the maximum value. (If the row is all nan then it would never be equal so do not count on equal). So < is never true so the statements inside the if are never done.
@Walter Roberson: excuse me, I think the condition is not really a problem because maxRow has value for each loop. So, after the comparison between maxRow and Pnpo(i,j) is true condition, the value of maxRow will be established in the first task
maxRow = Pnpo(i,j);
but the next task isn't executed
mark = j
and that is the point.
@Nuec, since maxRow is already the maximum value in the current row, therefore the condition
maxRow < Pnpo(i,j)
never becomes true, and the execution never reaches
mark = j
If you are looking for the index of the maximum then use the two-output form of max()
@Walter Roberson: Thank you. That is better idea for this situation.

Sign in to comment.

 Accepted Answer

You can solve the issue mentioned by @Walter in the comment by initializing the maxRow with the lowest possible value. Change
maxRow = max(Pnpo(i,:))
to
maxRow = -inf;
and you code should run fine.
You can also avoid the for loop altogether by shown below
close all; clc; clear
[x,y] = meshgrid(-2:2,-2:2);
[xlength,ylength] = size(x);
r = zeros(xlength,ylength);
s = zeros(xlength,ylength);
Pnpos = zeros(xlength,ylength);
Pnpo = 3*x.*x.*y - x.*y + 2*y + x - 7;
[~, subs] = max(Pnpo, [], 2);
index = sub2ind(size(Pnpo), 1:xlength, subs');
Pnpos(index) = Pnpo(index);

More Answers (0)

Categories

Asked:

on 7 Mar 2020

Commented:

on 7 Mar 2020

Community Treasure Hunt

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

Start Hunting!