CaptainProg
CaptainProg

Reputation: 5690

MATLAB: 'If' any row of a part of an array contains a value

Is there any way of shortening line #2 of the code below?

for i = 1:length(dataStructure)
    if dataStructure(1,i) == 100000000 || dataStructure(2,i) == 100000000 % this line
        dataStructure(:,i) = NaN;
    end
end

I would have thought the following would suffice (but this doesn't work):

if dataStructure(:,i) == 100000000

In other words, how do I check whether a number exists in a given column of an array? The issue here is that I cannot predict whether dataStructure will have one or two rows, and so can't use a nested for loop, since it would cause an error every time dataStructure only had one row.

Upvotes: 1

Views: 1780

Answers (2)

Gunther Struyf
Gunther Struyf

Reputation: 11168

You don't need the loop:

dataStructure(:,any(dataStructure==1e8,1) = NaN;

this is called logical indexing, more info: here and here

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272832

if any(dataStructure(:,i) == 100000000)

Upvotes: 2

Related Questions