如何从for循环中存储值

时间:2014-05-26 15:55:40

标签: matlab for-loop

我想在以下内容中存储x_errory_errorz_error的值:

for i=1:0.1:5

    ly=i;

    for j=1:0.1:5;

        lx=j;

        c1=co1(x1,y1,z1,lx,ly,lz,f);
        c2=co2(x2,y2,z1,lx,ly,lz,f);
        c3=co3(x3,y3,z1,lx,ly,lz,f);

        %options = optimoptions('fsolve','Display','iter');

        func = @(x)efunction(x,x1,x2,x3,y1,y2,y3,c1,c2,c3,f);

        [x,fval] = fsolve(func,x0);


        X=x(1,1);
        Y=x(1,2);
        H=x(1,3);

        x_error= sprintf('%.10f',abs(X-lx));
        y_error=sprintf('%.10f',abs(Y-ly));
        z_error=sprintf('%.10f',abs((z1-H)-lz));

    end

end

我想存储x_errory_errorz_error的所有值。

1 个答案:

答案 0 :(得分:0)

您可以将字符串存储在单元格数组中:

% init arrays
num_iterations = size(1:0.1:5, 2);
x_errors = cell(num_iterations,1);
y_errors = cell(num_iterations,1);
z_errors = cell(num_iterations,1);

for j=1:0.1:5;

    % some code
    % ...


    x_error= sprintf('%.10f',abs(X-lx));
    y_error=sprintf('%.10f',abs(Y-ly));
    z_error=sprintf('%.10f',abs((z1-H)-lz));

    store_index = int32(j*10) - 9;
    x_errors{store_index} = x_error;
    y_errors{store_index} = y_error;
    z_errors{store_index} = z_error;
end

但是,我建议将错误的数值存储在常规数组中,然后在需要时使用sprintf格式化它们。

存储您要执行的数值

% init/allocate memory
num_iterations = size(1:0.1:5, 2);
x_errors = zeros(num_iterations,1);
% ...
x_error = abs(X-lx);
% ...
x_errors(store_index) = x_error;