How to compare multiple variables against one and produce an answer for each comparison?

6 ビュー (過去 30 日間)
Lauren
Lauren 2022 年 11 月 28 日
コメント済み: Stephen23 2022 年 11 月 29 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by