Search code examples
matlabmatrixcompiler-errorsconditional-statementsedit

MATLAB - Editing a portion of a matrix with conditions


I know that editing a matrix with conditions is done this way:

X = [1 1 0 0; 
     0 0 1 1; 
     1 0 1 0; 
     0 0 1 0]

X(X==0) = 1

I want to apply the conditional changes only to the lower half of the matrix and I've tried doing this.

X(3:4,1:4)(X==0) = 1;

But an error is returned: "Error: Invalid array indexing."


Solution

  • Your logical indexing condition is X==0.

    You can modify this logical index such that the half you don't want to modify is false.

    idx = (X==0);       % condition
    idx(1:2,:) = false; % don't modify rows 1-2 with this index
    X( idx ) = 1;       % modify the array according to elements where idx is true
    

    You can define idx in one line if you want, although this is probably less clear

    idx = (X==0) & ((1:size(X,1)).' >= 3); % define condition including row number >= 3
    X( idx ) = 1;