Search code examples
matlabmatrixconditional-statementscriteriaassign

Assign new matrices for a certain condition, in Matlab


I have a matrix,DataFile=8x8. One of those columns(column 6 or "coarse event") can only be 0 or a 1. It will be 0 for a non-stable condition and 1 for a stable condition.Now for the example:

DataFile = [ 11 5 66 1.2 14.1 0 -1 0.1;...
             12 6 67 1.4 15.1 0 -1 0.1;...
             13 7 68 1.6 16.1 1 -1 0.2;...
             14 8 69 1.7 16.5 1 -2 0.1;...
             15 9 68 1.6 16.2 0 -1 0.3;...
             16 8 66 1.3 15.7 1 -2 0.0;...
             17 5 65 1.5 16.1 1  0 0.0;...
             18 6 66 1.2 16.6 0  1 1.0];

With slight changes from the code in the comments:

DataFile =[zeros(1,size(DataFile,2)); DataFile; zeros(1,size(DataFile,2))];    
startInd = [find(diff(DataFile(:,6))==1)]; 
endInd   = [find(diff(DataFile(:,6)) <0)];

B={};
for n=1:1:numel(endInd)
    B(n)={DataFile(startInd(n):endInd(n),:)};
end

FirstBlock=B{1};
SecondBlock=B{2};

The result is 2 matrices(FirstBlock=3x8,SecondBlock=3x8), which wrongfully includes 0's in the 6th column. It should be giving two matrices(dataIs1(1)=2x8 and dataIs1(2)=2x8), with only 1's in the 6th column.

In reality I would like have the a n-amount of matrices, for which the "coarse event" is 1. Thank you for the help!


Solution

  • The magic word is logical indexing:

    If you have a Matrix A:

    A=[1 2 3 4 5;...
       0 6 7 8 9;...
       1 7 8 9 10]
    

    you can extact Row 1 and 2 by:

    B=A(A(:,1)==1)
    

    Hope thats waht your looking for, have fun.

    To seperate the groups we need to know where they start and end:

    endInd   = [find(diff(A(:,1))<0) size(A,1)]
    startInd = [1 find(diff(A(:,1))==1)]
    

    Then assigne the Data to arrays:

    B={};
    for n=1:1:numel(endInd)
        B(n)={A(startInd(n):endInd(n),:)};
    end
    

    Edit: Your new Data:

    DataFile = [ 11 5 66 1.2 14.1 0 -1 0.1;...
             12 6 67 1.4 15.1 0 -1 0.1;...
             13 7 68 1.6 16.1 1 -1 0.2;...
             14 8 69 1.7 16.5 1 -2 0.1;...
             15 9 68 1.6 16.2 0 -1 0.3;...
             16 8 66 1.3 15.7 1 -2 0.0;...
             17 5 65 1.5 16.1 1  0 0.0;...
             18 6 66 1.2 16.6 0  1 1.0];
    

    I add some padding to avoid mistakes:

    DataFile =[zeros(1,size(DataFile,2)); DataFile; zeros(1,size(DataFile,2))]
    

    Now, as before, we look for the starts and ends of the blocks:

     endInd   = [find(diff(A(:,1)) <0) -1]
     startInd = [find(diff(A(:,1))==1)]
    

    Then assigne the Data to a cell in a arrays:

    B={};
    for n=1:1:numel(endInd)
        B(n)={A(startInd(n):endInd(n),:)};
    end
    

    If you want to retrive, say, the second block:

    secondBlock=B{2};