Comparing numerical values of a 5x2 cell
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
the cyclist
2020-3-31
编辑:the cyclist
2020-3-31
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.
回答(2 个)
Image Analyst
2020-3-31
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 个评论
Image Analyst
2020-3-31
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
2020-3-31
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,:);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!