Search code examples
arraysmatlabloopsif-statementcell

MATLAB: Remove specific elements from array


Question 1: I have a 1x15 array, comprising of positive integers and negative integers. I wish to implement a MATLAB code which keeps all positive integers and skips the cells with negative contents.

I have tried the following:

X = [1 2 3 4 5 -10 1 -5 4 6 8 9 2 4 -2];
[r c] = size(X);
for i=1:r
    for j=1:c
        if X(i,j)<0
            X(i,j)=X(i,j+1)
        end
    end
end

The output should be:

X_new = [1 2 3 4 5 1 4 6 8 9 2 4]

How do I do this?


Question 2:

X = [1 2 3 4 5 -10 1 -5 4 6 8 9 2 4 -2]
Y = [5 3 8 9 4  5 6  7 4 7 9 5 2 1  4]

From Question 1,

X_new = [1 2 3 4 5 1 4 6 8 9 2 4]

I need to delete the corresponding values in Y so that:

Y_new = [5 3 8 9 4 6 4 7 9 5 2 1]

How do I perform this?


Solution

  • In MATLAB, manipulating arrays and matrices can be done much easier than for-loop solutions, in your task, can do find and delete negative value in the array, simply, as follows:

    Idx_neg = X < 0;  % finding X indices corresponding to negative elements
    X ( Idx_neg   ) = [];  % removing elements using [] operator
    
    Y ( Idx_neg  ) = [];   % removing corresponding elements in Y array