2
votes

I am trying to vectorize an if statement in Matlab and I am not sure how to do it. I want to assign a 'N' for positive values and 'S' for negative values. I want to avoid a for loop but here is my code:

LatDD = [23.0,12.3,-43.2,9.9,-40.7];
LatDir = ['' '' '' '' ''];
if (LatDD < 0)
    LatDir = 'S'
else
    LatDir = 'N'
end

Obviously this fails to do what I want because it really only checks the first element of LatDD. I could easily do a for loop but I want it to be vectorized. I tried logical indexing but all that got me was another vector with zeroes or ones which I would have to check with a for loop anyway.

2

2 Answers

5
votes

You can use logical indexing here, you just have to do it twice

LatDD = [23.0,12.3,-43.2,9.9,-40.7];
LatDir = ['' '' '' '' ''];

LatDir(LatDD < 0) = 'S';
LatDir(LatDD >= 0) = 'N';

Since you have a binary choice here, you could even skip a step by prefilling LatDir with all 'N' and just changing the ones corresponding to negative LatDD values to 'S'

LatDD = [23.0,12.3,-43.2,9.9,-40.7];
LatDir = ['N' 'N' 'N' 'N' 'N'];

LatDir(LatDD < 0) = 'S';
2
votes

Here's a one-liner -

char('S'*(LatDD<0) + 'N'*(~(LatDD<0)))

Sample run -

>> LatDD = [23.0,12.3,-43.2,9.9,-40.7];
>> LatDir = ['' '' '' '' ''];
>> char('S'*(LatDD<0) + 'N'*(~(LatDD<0)))
ans =
NNSNS