Matlab 如何将FOR循环的所有迭代结果输出到矩阵中并绘制图形

Matlab 如何将FOR循环的所有迭代结果输出到矩阵中并绘制图形,matlab,Matlab,我有两个嵌套格式的for循环。我的第二个循环计算最终的方程式。结果显示在第二个循环之外,以便在第二个循环完成时显示 下面是我在MATLAB中使用的逻辑。我需要绘制eqn2vs x的图形 L=100 for x=1:10 eqn1 for y=1:L eqn2 end value = num2strn eqn2 disp value end 目前我面临的问题是,eqn2的值或输出总是在每个周期后被替换,直到x达

我有两个嵌套格式的
for
循环。我的第二个循环计算最终的方程式。结果显示在第二个循环之外,以便在第二个循环完成时显示

下面是我在MATLAB中使用的逻辑。我需要绘制
eqn2
vs x的图形

L=100
for x=1:10
    eqn1
       for y=1:L
          eqn2
       end 
       value = num2strn eqn2
       disp value
end
目前我面临的问题是,
eqn2
的值或输出总是在每个周期后被替换,直到
x
达到10。因此,
eqn2
和value的工作空间表仅显示最后一个值。我的目的是记录从1:10开始的每个x周期中
value
的所有输出值


我怎样才能做到这一点呢?

你的伪代码对我来说有点太强了——我已经试着重新构建你想要做的事情。如果我理解正确,这应该解决您的问题(将计算的中间结果存储在数组Z中):

至于您在评论中提出的其他问题,您可能会从以下方面获得灵感:

L = 100;
nx = 20; ny = 99;  % I am choosing how many x and y values to test
Z = zeros(ny, nx); % allocate space for the results
x = linspace(0, 10, nx); % x and y don't need to be integers
y = linspace(1, L, ny);
myFlag = 0;              % flag can be used for breaking out of both loops

for xi = 1:nx            % xi and yi are integers
    for yi = 1:ny
         % evaluate "some function" of x(xi) and y(yi)
         % note that these are not constrained to be integers
         Z(yi, xi) = (x(xi)-4).^2 + 3*(y(yi)-5).^2+2;

         % the break condition you were asking for
         if Z(yi, xi) < 5
             fprintf(1, 'Z less than 5 with x=%.1f and y=%.1f\n', x(xi), y(yi));
             myFlag = 1; % set flag so we break out of both loops
             break
         end
    end
    if myFlag==1, break; end % break out of the outer loop as well
end
等等


如果你不能从这里找到答案,我就放弃…

嗨,我试过这个,它很管用。我能够存储每个循环结束时的“Z”值,但当我绘制它时,出现了一个错误。我认为这是因为“z”和“x”的大小不同。简单的绘图要求x和z的大小相同。知道如何处理这个问题吗?试着在plot命令中使用
z'
(转置)。什么是
大小(z)
大小(x)
?在我的例子中,z是(10乘100),x是10(1by1)。我猜在工作区中,X的最后一个值已注册。对不起,我怀疑我是否需要在循环中添加一个条件,以便z(y,X)感谢您的帮助。非常感谢你。
L = 100;
nx = 20; ny = 99;  % I am choosing how many x and y values to test
Z = zeros(ny, nx); % allocate space for the results
x = linspace(0, 10, nx); % x and y don't need to be integers
y = linspace(1, L, ny);
myFlag = 0;              % flag can be used for breaking out of both loops

for xi = 1:nx            % xi and yi are integers
    for yi = 1:ny
         % evaluate "some function" of x(xi) and y(yi)
         % note that these are not constrained to be integers
         Z(yi, xi) = (x(xi)-4).^2 + 3*(y(yi)-5).^2+2;

         % the break condition you were asking for
         if Z(yi, xi) < 5
             fprintf(1, 'Z less than 5 with x=%.1f and y=%.1f\n', x(xi), y(yi));
             myFlag = 1; % set flag so we break out of both loops
             break
         end
    end
    if myFlag==1, break; end % break out of the outer loop as well
end
highestZ = max(Z, [], 1); % "take the highest value of Z in the 1 dimension
fprintf(1, 'Z is always < 5 for x = %d\n', x(highestZ<5));