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
Walter Roberson
2020년 3월 7일
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.
Ameer Hamza
2020년 3월 7일
@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
Walter Roberson
2020년 3월 7일
If you are looking for the index of the maximum then use the two-output form of max()
Nuec Tah
2020년 3월 7일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!