Search code examples
matlabif-statementfor-loopstoring-data

Storing data in matrix in for and if loops


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

Solution

  • 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