Clear Filters
Clear Filters

fun is doing odd things

1 view (last 30 days)
John Hey
John Hey on 23 Jun 2023
Moved: John D'Errico on 23 Jun 2023
I have defined a function fun
fun=@(refprice,r)sum((prices-refprice*ot+(exp(-r*t).*ot')').^2);
and it works for any parameters refprice and r.
For example
fun(4.5,0.1)
ans =
1.1802e+04
>> when I put refprice0=4.5 and r0=0.1 i get
refprice0=4.5
refprice0 =
4.5000
>> r0=0.1
r0 =
0.1000
>> fun(refprice0,r0)
ans =
1.1802e+04
So it works.
But when I write
pars0=[refprice0,r0]
pars0 =
4.5000 0.1000
>> fun(pars0)
I get
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of
rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise
multiplication.
Error in analysedata>@(refprice,r)sum((prices-refprice*ot+(exp(-r*t).*ot')').^2) (line 13)
fun=@(refprice,r)sum((prices-refprice*ot+(exp(-r*t).*ot')').^2);
How can fun(refprice0,r0) work but not pars0=[refprice0,r0] and fun(pars0)???

Answers (1)

VBBV
VBBV on 23 Jun 2023
Edited: VBBV on 23 Jun 2023
fun is defined as anonymous function with two input parameters. In the 1st approach, you are defining both parameters as arguments to the anonymous function.
% 1st approach
prices = 10; ot = 20; t = 10; % e,g values
fun=@(refprice,r) sum((prices-refprice*ot+(exp(-r*t).*ot')').^2)
fun = function_handle with value:
@(refprice,r)sum((prices-refprice*ot+(exp(-r*t).*ot')').^2)
fun(4.5,0.1)
ans = 5.2769e+03
% 2nd approach
refprice = 4.5;
r0 = 0.1;
pars0=[refprice,r0]
pars0 = 1×2
4.5000 0.1000
fun(pars0(1),pars0(2))
ans = 5.2769e+03
In the 2nd approach however, both parameters are defined as vector but still needs to be passed as 2 arguments as shown above. In both cases, it should yield same values.
In your case, you are passing the entire vector as single input parameter ignoring the other parameter. Since, the anonymous function contains multiplication operator, it expects a element wise multiplication when there is vector and throws an error when there are incorrect dimensions for the variables, which the error clearly states.
  1 Comment
John Hey
John Hey on 23 Jun 2023
Moved: John D'Errico on 23 Jun 2023
Dear VBBV,
Many thanks for your answer.
John

Sign in to comment.

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!