필터 지우기
필터 지우기

How to Loop this function

조회 수: 1 (최근 30일)
Brittany Isbister
Brittany Isbister 2021년 2월 14일
댓글: Brittany Isbister 2021년 2월 14일
Hi All!
I have this code down below that I am using. I need to loop a function I have so it works and I can display certain messages for certain output values of the function. I have the function working when i'm not trying to do this
this is my function:
function [helpIndex]=needsHelp(age,dur,burden,sati) %function to calculate the helpIndex
helpIndex=0;
if (age>50)
helpIndex=helpIndex + 1;
end
if (dur>60)
helpIndex=helpIndex + 1;
end
if (burden>70)
helpIndex=helpIndex + 1;
end
if (burden>70 & sati<50)
helpIndex=helpIndex + 1;
end
end
This is the script that I currently have and I am trying to make it so the above function can loop through all of my vlaues and so I can output different sayings when I have a helpIndex between 1 and 2 and when I have one greater than 2.
Here is my script:
%% Part A
T=readtable('Caregivers.xlsx','Range','A1:K101')
A=table2array(T);
age=A(1:100,2);
ageAvg=mean(age)
sdevAge=std(age)
dur=A(1:100,4);
avgDur=mean(dur)
sdecDur=std(dur)
burden=A(1:100,10);
avgBurden=mean(burden)
sdevBurden=std(burden)
sati=A(1:100,11);
avgSat=mean(sati)
sdevSat=std(sati)
%% Part B
percieved=A(1:100,9);
subplot(2,1,1)
scatter(burden,sati)
xlabel('Burden')
ylabel('Satisfaction')
title('Satisfaction vs. Burden')
subplot(2,1,2)
scatter(percieved,sati)
xlabel('Percieved Social Support')
ylabel('Satisfaction')
title('Satisfaction vs.Percieved Social Support ')
%% Part C
for age=1:100 burden=1:100 dur=1:100 sati=1:100
[helpIndex]=needsHelp(age,dur,burden,sati)
helpIndex>1 & helpIndex <=2
fprintf('Caregiver <insert caregiver ID> needs help.')
helpIndex<2
fprintf('Warning: Caregiver <insert caregiver ID> needs considerable help')
end
Thank you for all of your help!
  댓글 수: 2
Stephen23
Stephen23 2021년 2월 14일
If you vectorized the function you would not need any loops at all:
function helpIndex = needsHelp(age,dur,burden,sati)
helpIndex = (age>50) + (dur>60) + (burden>70) + (burden>70 & sati<50);
end
Brittany Isbister
Brittany Isbister 2021년 2월 14일
Hi Stephen!
Thank you worked! I'm just wondering if you have any suggestions on how I could add the comments in now for when the values are greater than 2? Thank you for all of your help! :)

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

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