How to customize a function

2 views (last 30 days)
Orongo
Orongo on 29 Oct 2018
Reopened: Walter Roberson on 20 Dec 2018
Hi, I need to amend my function f_lx.m. Today the function takes 2 parameters; t=age and param_1955=a vector with 3 scalars. I want different parameters to be used depending on age. The function looks like this
function res=f_lx(x,param)
a=param(1);
b=param(2);
c=param(3);
res = zeros(size(x));
ind = x>100;
res(ind) = a+b*exp(c*100)+(x(ind)-100)*0.001;
res(~ind) =a+b*exp(c*x(~ind));
end
Now I have more sets of parameters; param_1938 and param_1945. Given the age x, different parameters will be used - here is a table demonstrating what I mean
x parameter
65 param_1955
66 param_1955
67 param_1955
68 param_1955
69 param_1955
70 param_1945
71 param_1945
72 param_1945
73 param_1945
74 param_1945
75 param_1945
76 param_1945
77 param_1938
78 param_1938
79 param_1938
... param_1938
106 param_1938
How can I change my f_lx.m to consider other parameters given age?
  1 Comment
Stephen23
Stephen23 on 29 Oct 2018
Numbered parameter names is a sign that you are doing something wrong. You should use indexing to write simpler, more efficient code.

Sign in to comment.

Answers (2)

KSSV
KSSV on 29 Oct 2018
function res=f_lx(x,param)
a=param(:,1);
b=param(:,2);
c=param(:,3);
res = zeros(size(x));
ind = x>100;
res(ind) = a(ind)+b(ind).*exp(c(ind)*100)+(x(ind)-100)*0.001;
res(~ind) =a(~ind)+b(~ind).*exp(c(~ind).*x(~ind));
end
Your x and param can me arrays now.
  1 Comment
Orongo
Orongo on 29 Oct 2018
Edited: Orongo on 29 Oct 2018
Hi, so I created
param = [param_1938; param_1945; param_1955];
=
2.04021590146881e-10 1.72224144676415e-06 0.123947876025562
0.00463638421048442 4.97805451254727e-07 0.137338003231075
0.00467255690390434 1.90218641756575e-07 0.147616811690677
and get the error
Error in f_lx (line 10)
res(~ind) =a(~ind)+b(~ind).*exp(c(~ind).*x(~ind));
I think is because param is a matrix and not a vector. Just to clarify; age 65-59 take param_1955 (row 1), age 70-76 takes param_1945 (row 2) and age 77-106 takes param 1938 (row 3).

Sign in to comment.


Orongo
Orongo on 30 Oct 2018
I have closed this query and raised it here to avoid confusion. https://uk.mathworks.com/matlabcentral/answers/427020-how-to-change-anonymous-function-to-take-array-parameter-and-subject-to-ranges

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!