【问题标题】:Storing data in matrix in for and if loops在 for 和 if 循环中将数据存储在矩阵中
【发布时间】:2011-09-22 16:15:43
【问题描述】:

我在将数据存储在 for 和 if 循环中的矩阵中时遇到问题,

结果只给了我最后一次迭代的最后一个值。我想要所有的

将所有迭代的结果存储在一个矩阵中。

这是我的代码示例:

clear all

clc

%%%%%%%%%%%%%%

 for M=1:3;

    for D=1:5;

%%%%%%%%%%%%%%

    if ((M == 1) && (D <= 3)) || ((M == 3) && (2 <= D  && D <= 5))

        U1=[5 6];

    else

        U1=[0 0];

    end

    % desired output: 

    % U1=[5 6 5 6 5 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 5 6 5 6 5 6]

%%%%%%%%%%%%%%

    if (M == 1) && (D==4) || ((M == 3) && (D == 1))

        U2=[8 9];

    else

        U2=[0 0];

    end

    % desired output: 

    % U2=[0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0]

%%%%%%%%%%%%%%

    if ((M == 1) && (D == 5)) || ((M == 2) && (1 <= D  && D <= 5)) 

        U3=[2 6];

    else

        U3=[0 0];

    end

    % desired output:

    % U3=[0 0 0 0 0 0 0 0 2 6 2 6 2 6 2 6 2 6 2 6 0 0 0 0 0 0 0 0 0 0]

 %%%%%%%%%%%%%%

    end
end

【问题讨论】:

    标签: matlab if-statement for-loop storing-data


    【解决方案1】:

    每次写 UX=[X Y]; 时都会覆盖矩阵。

    如果您想追加数据,可以预先分配矩阵并在每次分配新值时指定矩阵索引,或者写 UX=[UX X Y]; 直接在矩阵末尾追加数据。

    clear all
    clc
    U1=[];
    U2=[];
    U3=[];
    for M=1:3
        for D=1:5
            if ((M == 1) && (D <= 3)) || ((M == 3) && (2 <= D  && D <= 5))
                U1=[U1 5 6]; 
            else
                U1=[U1 0 0];
            end
            % desired output: 
            % U1=[5 6 5 6 5 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 5 6 5 6 5 6]
            if (M == 1) && (D==4) || ((M == 3) && (D == 1))
                U2=[U2 8 9];
            else
                U2=[U2 0 0];
            end
            % desired output: 
            % U2=[0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0 0 0 0 0 8 9 0 0 0 0 0 0 0 0]
            if ((M == 1) && (D == 5)) || ((M == 2) && (1 <= D  && D <= 5)) 
                U3=[U3 2 6];
            else
                U3=[U3 0 0];
            end
            % desired output:
            % U3=[0 0 0 0 0 0 0 0 2 6 2 6 2 6 2 6 2 6 2 6 0 0 0 0 0 0 0 0 0 0]
        end
    end
    

    【讨论】:

    • 能否通过简单的例子告诉我如何做到这一点。问候
    • 感谢 Aabaz,但 U1、U2 和 U3 未定义并且它给出错误:???未定义的函数或变量“U1”。
    • 好的,太好了,谢谢 Aabaz。问候
    【解决方案2】:

    您可以完全避免循环:

    [M,D] = meshgrid(1:3,1:5);
    M = M(:)'; D = D(:)';
    
    idx1 = ( M==1 & D<=3 ) | ( M== 3 & 2<=D & D<=5 );
    idx2 = ( M==1 & D==4) | ( M==3 & D==1 );
    idx3 = ( M==1 & D==5 ) | ( M==2 & 1<=D & D<=5 );
    
    U1 = bsxfun(@times, idx1, [5;6]); U1 = U1(:)';
    U2 = bsxfun(@times, idx2, [8;9]); U2 = U2(:)';
    U3 = bsxfun(@times, idx3, [2;6]); U3 = U3(:)';
    

    【讨论】:

    • 感谢 Amro,代码很好。我最后的目标是找到 U=U1+U2+U3 ,我们可以直接找到这个U而不找到U1,U2和U3
    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多