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!