# How to Loop this function

2 ビュー (過去 30 日間)
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
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 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 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! :)

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangePhysics についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by