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

조회 수: 12 (최근 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에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by