0

我有以下代码

x=[1 0.5 0.5]', iter=0; dxnorm=1;
while dxnorm>0.5e-4 & iter<10
    f=[cos(x(1))+cos(x(2))+cos(x(3))-2
        sin(x(1))+sin(x(2))+sin(x(3))
        tan(x(1))-2.*tan(x(2))+tan(x(3))
        ]                          ;
    J=[-sin(x(1))     -sin(x(2))      -sin(x(3))
        cos(x(1))      cos(x(2))      cos(x(3))
        tan(x(1)).^2 + 1    -2*tan(x(2)).^2 - 2     tan(x(3)).^2 + 1];
    dx=-J\f;
    x=x+dx;
    dxnorm = norm(dx,inf), iter=iter+1;
end
x, iter

我想将每次迭代后的结果存储在一个表中,这样我就可以看到随着时间的推移结果如何变化。我已经看到了一些关于如何执行此操作的不同代码(也就是说,您有一个 for 循环,并将每个结果存储在一个表中),但没有一个我能够实现。任何想法我怎么能做到这一点?例如,我确实从这里观看了一些示例,http://www.mathworks.com/matlabcentral/answers/163572-creating-a-table-of-values-from-for-loops但正如我所说的不能实施其中任何一项。

4

1 回答 1

2

您需要在循环的每次迭代期间使用迭代器来存储结果。例如,如果您想保存xdxnorm,您可以将它们存储在元胞数组的列中,而不必担心它们的大小不同。

x = [1 0.5 0.5]';
maxiter = 10;
iter = 0;
dxnorm = 1;
results = cell(maxiter + 1, 2); % Preallocate results array

while dxnorm > 0.5e-4 && iter <= maxiter
    f = [cos(x(1)) + cos(x(2))    + cos(x(3))-2; ...
         sin(x(1)) + sin(x(2))    + sin(x(3)); ...
         tan(x(1)) - 2.*tan(x(2)) + tan(x(3)); ...
         ];
    J = [-sin(x(1)),       -sin(x(2)),          -sin(x(3)); ...
         cos(x(1)),        cos(x(2)),           cos(x(3)); ...
         tan(x(1)).^2 + 1, -2*tan(x(2)).^2 - 2, tan(x(3)).^2 + 1 ...
         ];
    dx = -J\f;
    results{iter + 1, 1} = x;
    x = x + dx;
    dxnorm = norm(dx,inf);
    results{iter + 1, 2} = dxnorm;
    iter = iter + 1;
end

这为您提供了一个元胞数组results,其中第一列包含您的x数据,第二列包含dxnorm每次循环迭代的数据。您使用花括号{}对单元格数组的单元格进行索引,例如results{1, 1}为您提供x用于循环第一次迭代的数据。

于 2015-11-24T13:51:53.140 回答