开发者

Storing data in matrix in for and if loops

开发者 https://www.devze.com 2023-04-06 23:22 出处:网络
I have a problem in storing the data in matrix in for and if loops, The results give me only the last value of the last iteration. I want all the

I have a problem in storing the data in matrix in for and if loops,

The results give me only the last value of the last iteration. I want all the

results of all iterations to be stored in a matrix be sequence.

Here is a sample of my code:

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


You are overwriting your matrices each time you write UX=[X Y];.

If you want to append data, either preallocate your matrices and specify the matrix index each time you assign a new value, or write UX=[UX X Y]; to directly append data at the end of your matrices.

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


You can avoid the loops altogether:

[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(:)';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号