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
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
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)
ans = 1×2 string array
"ON" "QC"

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by