Home > Back-end >  I want to remove all the points that satisfy certain condition in matlab
I want to remove all the points that satisfy certain condition in matlab

Time:01-27

current plot

I want to remove all those data points that lies between 5 & 10 on x axis and 0 & 500 on y axis.

givenData is a 10000X2 matrix with data.

I've written the following code. What mistake am I making here? Also is there a better way to do this?

for i=1:10000
    if givenData(i,1)>5 && givenData(i,1)<10 && givenData(i,2)>0 && givenData(i,2)<500
        givenData(i,:) = [];
    end    
end    

plot(givenData(:,1),givenData(:,2),'b.','MarkerSize',5);hold
contour(xgrid,ygrid,Z,[4e-5, 4e-5],'EdgeColor',[1 0 0],'ShowText','on','LineWidth',2);

Any help is appreciated. Thank you.

CodePudding user response:

You’re deleting elements from the array as you iterate through it, so the next element shifts over into the deleted spot and gets skipped in the checking.

To fix this, you can either skip the loop entirely and use logical indexing:

givenData(givenData(:,1)>5 & givenData(:,1)<10 & givenData(:,2)>0 & givenData(:,2)<500,:) = [];

or iterate through the array backwards:

for i = 10000:-1:1

In general, avoiding the loop allows MATLAB to perform operations more quickly, with the trade off that the index arrays take more memory to process.

  • Related