How to compare multiple variables against one and produce an answer for each comparison?
6 次查看(过去 30 天)
显示 更早的评论
I calculated 4 different category averages, each is assigned to a variable (ON, BC, QC, & AB), and the total average (CAD). I want to compare each of the 4 averages to the total average, and if it is higher than the total average, it should list the variable name.
Initially I used the code:
fprintf('Areas with averages above the national average: ')
if ON>CAD
fprintf ('Ontario')
end
but not sure how to repeat this loop for the other 3 variables and produce the same response for all.
1 个评论
Stephen23
2022-11-29
"each is assigned to a variable (ON, BC, QC, & AB)"
Storing your data in lots of separate variables nakes this task much more complex.
The name "MATLAB" comes from "MATrix LABoratory", and when you store your data in matrices/vectors, then processing it becomes much easier, as David Hill shows. You should use matrices/vectors, just as MATLAB is designed for.
回答(1 个)
David Hill
2022-11-28
ON=5;BC=2;QC=4;AB=1;
L=["ON","BC","QC","AB"];%put names in string array
r=[ON,BC,QC,AB];%put all variables into a single array
CAD=mean(r);
L(r>CAD)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!