# Trying to do an if/and statement on a vector but have an addition apply to only one element of vector

4 views (last 30 days)
MathandPhysics on 23 May 2023
Commented: MathandPhysics on 23 May 2023
So I want to do something where you have a compass that goes from 0 to 360. But what I want to do is have it where you have the 360 rollover, aka, let's say data is going due north (aka hovering around 360) and oscillates between 350 and 10 degrees. Ultimately I want to plot this, but right now just trying to get the vectors to work. If you try to plot it, you'll get huge peaks and valleys, and can't discern patterns, so what you want to do is to add 360 to the values that flip around the 360 mark.
At the end is a sample code I generated. What I want it to do is the following: check and see if the data is more than 350 degrees, but less than 10 degrees, it adds 360 to that one value. So mathematically this is waht I mean:
350 -> OK
8 -> this is less than 10, greater than 350 so add 360 to this value ->368
355 -> OK
1 -> this is less than 10, greater than 350 so add 360 to this value ->361
359 ->OK
so direction vector output = [350; 368; 361;359]
the other thing this code should do is if those conditions aren't met, it just returns the original vector.
The problem is when I run this and any iteration I can think of, it either doesn't apply the conditions at all, or it adds 360 to all the numbers, not just the small numbers.
direction = [350; 8; 355; 1; 359];
for i = 1:length(direction)
if any(direction(i,:)) > 350 && any(direction(i,:)) < 10
direction(i,:) = direction(i,:) + 360
else
direction(i,:) = direction(i,:);
end
end

KSSV on 23 May 2023
direction = [350; 8; 355; 1; 359];
direction0 = direction ;
direction(direction<10)=direction(direction<10)+360
direction = 5×1
350 368 355 361 359
MathandPhysics on 23 May 2023
I removed the for loop, put what you did in the last line in my if/and statement and it does exactly what I needed it to do. Thanks!

### More Answers (1)

Matt J on 23 May 2023
Edited: Matt J on 23 May 2023
I think a better method would be to update the compass position incrementally, using the attached file cumangle.m
t=linspace(-1,1);
theta=180+20*cos(pi*t);
X=cosd(theta); Y=sind(theta); %coordinates of compass tip
plot(t,180+atan2d(Y,X), t, 180+cumangle(Y,X),'x');
legend('atan2','cumangle',location='southeast')
xlabel t; ylabel 'Angle (deg.)'

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2018b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!