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

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.
Nuec Tah
Nuec Tah 2020년 3월 7일
편집: Nuec Tah 2020년 3월 7일
@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()
Nuec Tah
Nuec Tah 2020년 3월 7일
@Walter Roberson: Thank you. That is better idea for this situation.

댓글을 달려면 로그인하십시오.

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 3월 7일

0 개 추천

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);

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2020년 3월 7일

댓글:

2020년 3월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by