Finding a series of numbers in a vector which correspond with a series of numbers in a different vector.

2 views (last 30 days)
I Have two vectors for example,
Yaw = [9 9 8 9 10 10 10 10 14 15 15 15 15];%Degrees,
Speed = [212 212 213 180 200 190 200 200 200 210 210 210 150];%KNOTS
I need to count the number of times Yaw is at 9 and Speed above 210. In other words
for i = 1:length(Yaw)
if Yaw(i) == 9 && Speed(i) >= 210;
count9 = count9 + 1;
elseif Yaw(i) == 10 && Speed(i) >= 200;
count10 = count10 + 1;
elseif Yaw(i) == 15 && Speed(i) >= 150;
count15 = count15 + 1;
end
end
Is there a more efficient way. The vectors I am working with are very large. I also need to know the indices. i.e. the exact speed at the 9 10 or 15 degrees yaw in order to perform further calculations.
I'd appreciate any advice. Thanks

Accepted Answer

Stephen23
Stephen23 on 8 Feb 2016
Edited: Stephen23 on 8 Feb 2016
The most efficient way is to write vectorized code:
Yaw = [ 9, 9, 8, 9, 10, 10, 10, 10, 14, 15, 15, 15, 15]; % Degrees
Speed = [212,212,213,180,200,190,200,200,200,210,210,210,150]; % KNOTS
Ychk = [ 9; 10; 15];
Schk = [210;200;150];
Yidx = bsxfun(@eq,Yaw, Ychk);
Sidx = bsxfun(@ge,Speed,Schk);
idx = Yidx & Sidx; % these are the indices
sum(idx,2)
this shows the answer in the command window:
ans =
2
3
4
(two values with Yaw==9 and speed>=210, three values with yaw==10 and speed>=200, four values with yaw==15 and speed>=150). Note that the orientation of the inputs to bsxfun is critical, and that each row of the output variable idx corresponds to one pair of the "check" values.
PS: Don't create separate variables with meta-data in their names (e.g. yaw). Although beginners love doing this it always leads to bad programming decisions later. Keep your data in as few variables as possible. Because I keep the outputs in single variables it means the code will adapt automatically when you change the input values or number of input checks. Code like this is simpler and more adaptable: don't put meta data into your variable names! Here is why:

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!