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

2 次查看(过去 30 天)
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
KSSV 2023-5-23
direction = [350; 8; 355; 1; 359];
direction0 = direction ;
direction(direction<10)=direction(direction<10)+360
direction = 5×1
350 368 355 361 359

更多回答(1 个)

Matt J
Matt J 2023-5-23
编辑:Matt J 2023-5-23
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.)'

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by