# How to customize a function

1 ビュー (過去 30 日間)
Orongo 2018 年 10 月 29 日

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 件のコメント表示非表示 なし
Stephen23 2018 年 10 月 29 日
Numbered parameter names is a sign that you are doing something wrong. You should use indexing to write simpler, more efficient code.

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

### 回答 (2 件)

KSSV 2018 年 10 月 29 日
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 件のコメント表示非表示 なし
Orongo 2018 年 10 月 29 日
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).

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

Orongo 2018 年 10 月 30 日
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

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

### Community Treasure Hunt

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

Start Hunting!

Translated by