2

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 Answers 2

5

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'; 
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! Thank you
2

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 

1 Comment

This also works but it is confusing for beginners like me. Thanks for answering though. It helps me and others learn the tricks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.