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!