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:rfor j=1:cif X(i,j)<0X(i,j)=X(i,j+1)endendend

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?

1

Best Answer


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 elementsX ( Idx_neg ) = []; % removing elements using [] operatorY ( Idx_neg ) = []; % removing corresponding elements in Y array