For loop for a function
조회 수: 1 (최근 30일)
이전 댓글 표시
I have the following function and I want to run it for age 30 to 100. I think I need to develop a for loop here. Can anyone please help me out? I know if I change the value of age step by step like 30, 31 .... then I can do it but I need to run it as a for loop
function hf = myfun(age)
age = [30:100]
hf = zeros(5,5);
hf(1,2) = exp(-0.0625.*age-0.0134); % exp(age effect+time effect)
hf(1,5) = exp(-9.65573+0.01844+0.08218*age+0.02246); % exp(intercept+ age effect+time effect)
hf(2,3) = exp(-1.6660-0.1116.*age-0.0025); % exp(intercept+ age effect+time effect)
hf(2,4) = exp(-8.96236+0.07691.*age + 0.00978); % assuming the death rate of male of same age(Hubener et al.)
hf(2,5) = exp(-9.65573+0.08218.*age+0.02246); % self-mortality
hf(3,2) = exp(-0.0625.*age-0.0134+0.0676); %exp(intercept+ age effect+time effect+marriage once before)
hf(3,5) = exp(-9.65573+0.08218.*age+0.02246-0.11853);
hf(4,2) = exp(-0.4176-0.0625-0.0134.*age);
hf(4,5) = exp(-9.65573+0.08218.*age+0.02246-0.00415);
hf(1,1) = -(hf(1,2)+hf(1,5))
hf(2,2) = -(hf(2,3)+hf(2,4)+hf(2,5))
hf(3,3) = -(hf(3,2)+hf(3,5))
hf(4,4) = -(hf(4,2)+hf(4,5))
end
댓글 수: 0
채택된 답변
Jakob B. Nielsen
2021년 2월 15일
You construct the for loop like this:
for i=1:size(age,2) %by referencing your age array, you can change the age values and it will still work
hf(i,:,:) = zeros(5,5);
hf(i,1,2) = exp(-0.0625.*age(i)-0.0134); %index every step of hf to rely on i, and use the i'th value of age for the evaluations of the whole way
end
In the end, you will have hf(1,:,:) contain your results from age(1) in this case age=30, hf(2,:,:) age = 31 and so on.
댓글 수: 6
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!