Mike
Mike

Reputation: 47

Matlab: Problem with deleting rows from an array if a certain condition is true

After creating a dataset array (data), I want to delete all rows for which Var4 takes a certain value. Here is what I've done so far:

for i=1:length(data.perf)
    if data.Var4(i)==2
        data(i,:)=[]
    end
end

The problem of course is that the array gets shorter in every run the condition holds true, so that it stops before all lines are checked. When i=length(data.perf) the array is some 50 lines shorter. I think you guys get the problem. Can somebody please suggest me an elegant solution? I will have to do things like this quite often in the future.

Upvotes: 0

Views: 1460

Answers (1)

groovingandi
groovingandi

Reputation: 2006

Are you sure you want to loop to length(data.perf) and not just length(data)? It's not clear from the context but would make more sense...

First suggestion: Reversing your loop could solve the problem of the array getting shorter (for i = length(data.perf):-1:1...)

The more elegant solution would be to do it without a for loop

data(data.Var4==2, :) = [];

Upvotes: 5

Related Questions