Creating a column vector form data in table to meet specific requirements.

I tried so many times to write a vector that meet specific requirements but it gave me scalar.
The requirements are:
If their age is greater than 75 or their BMI is greater than 50 I want the variable risk to a value of 3, signifying high risk. If their age is greater than 50 and less than or equal to 75 and their BMI is greater than 40 and less than or equal to 50, then I want the variable risk for that subject to 2 (medium risk) and if they don't fit any of the above criteria I would like their risk to 1, signifying low risk.
Notice both (BMI and age are vector of 20x1 double)
My code is
for index=1:length(age)
for index_1=1:length(BMI)
if age>75
risk(high_risk) = 3;
elseif (age>50 & age<=75)
risk(medium_risk) = 2;
elseif (BMI>50)
risk(high_risk) =3;
elseif ( BMI>40 & BMI<=50)
risk(medium_risk)=2
else
risk=1
end
end
end

 Accepted Answer

risk=ones(size(age));
risk(age>75|BMI>50)=3;
risk(age>50&age<=75&BMI>40&BMI<=50)=2;

8 Comments

Nice answer, good use of MATLAB.
If the order is revised the logic can be simplified:
risk = ones(size(age));
risk(age>50 & BMI>40) = 2;
risk(age>75 | BMI>50) = 3;
I do not get it !
Do I wirte them in the if conditional_expression?
The code is just that simple:
risk = ones(size(age));
risk(age>50 & BMI>40) = 2;
risk(age>75 | BMI>50) = 3;
You are indexing into the risk vector for the conditions and setting the resk vector appropriately.
"Do I wirte them in the if conditional_expression? "
No, that is the answer. Writing MATLAB code using logical indexing (like this answer) is often simpler than using loops and lots of IFs (like you did). Logical indexing is one of MATLAB's superpowers, learn how to use it:
@Stephen if I am only seeking for the for data that equal 1 & 2 which is low and medium risk , but I would like to crop data 20x5 table to only include low and medium risk , would the following code be right ?
eligible_participants_1=risk(:,1)==1 ;
eligible_participants_2=risk(:,1)==2 ;
total_eligible_participants=eligible_participants_1+eligible_participants_2;
selected_participants= participants(eligible_participants_1);
@Hassen Mohamed Yousif Abdelatif: you can also use logical indexing, e.g.:
idx = risk(:,1)==1 | risk(:,1)==2; % or ISMEMBER
selected_participants = participants(idx,:)
Thanks @Stephen for getting back.
If that would give me the selected_participants that I am looking for, why is it 10x5 table instead of 20x5 table?
Apparently because only ten participants meet those requirements.
If you have a 20x5 table and select 10 rows from it then you will get a 10x5 table.

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

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

Start Hunting!