Comparing numerical values of a 5x2 cell
10 views (last 30 days)
Show older comments
Hello,
I am trying to compare all values in a 5x2 array that are below a certain threshold, and preserve the corresponding data in its particular row. For example, let's say I have a total of 5 cars but need to check which car goes a certain speed. I have a 5x2 matrix where the first column is a string and the second column are integers. I need to develop an algorithm that will return each of the cars that is below a a certain speed, say, below equal to or below 55 mph:
Red Car 50
Blue Car 45
Green Car 30
Black Car 60
Yellow Car 55
Therefore my output would need to be:
Red Car 50
Blue Car 45
Green Car 30
Yellow Car 55
I am guessing that the best way to do this will be with a few loops and an if statement to check the condition, but I am just not sure how to go about this as I am pretty new to MatLab. Any tips would be appreciated.
Thanks,
Patrick
2 Comments
the cyclist
on 31 Mar 2020
Edited: the cyclist
on 31 Mar 2020
How are your car data stored? In a cell array? A table? Can you upload the data in a *.mat file, instead of just describing it?
Also, I don't understand how the 2x2 array you mention comes into play.
Answers (2)
Image Analyst
on 31 Mar 2020
This will do it:
ca = {
'Red Car', 50;
'Blue Car', 45;
'Green Car', 30;
'Black Car', 60;
'Yellow Car', 55}
speeds = vertcat(ca{:, 2}) % Extract column 2.
slowSpeeds = speeds < 55 % See who is below 55
output = ca(slowSpeeds, :) % Extract only those below 55.
3 Comments
Image Analyst
on 31 Mar 2020
Wow, how/why did it get so complicated??? Try to avoid that. Like Akira says, use a table - that's the current best approach.
Anyway, attach your actual cell array in a .mat file and I'll try to straighten it out or simplify it.
Akira Agata
on 31 Mar 2020
I would recommend storing your data as a table variable before processing, like:
% Data
ca = {
'Red Car', 50;
'Blue Car', 45;
'Green Car', 30;
'Black Car', 60;
'Yellow Car', 55};
% Arrange to table
T = table(ca(:,1),cell2mat(ca(:,2)),'VariableNames',{'CarType','Speed'});
% Extract the data where speed <= 55 mph
idx = T.Speed <= 55;
Tout = T(idx,:);
See Also
Categories
Find more on Multidimensional Arrays 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!