fun is doing odd things
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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)???
Respuestas (1)
VBBV
el 23 de Jun. de 2023
Editada: VBBV
el 23 de Jun. de 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(4.5,0.1)
% 2nd approach
refprice = 4.5;
r0 = 0.1;
pars0=[refprice,r0]
fun(pars0(1),pars0(2))
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 comentario
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!