fun is doing odd things

2 vues (au cours des 30 derniers jours)
John Hey
John Hey le 23 Juin 2023
Déplacé(e) : John D'Errico le 23 Juin 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)???

Réponses (1)

VBBV
VBBV le 23 Juin 2023
Modifié(e) : VBBV le 23 Juin 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 commentaire
John Hey
John Hey le 23 Juin 2023
Déplacé(e) : John D'Errico le 23 Juin 2023
Dear VBBV,
Many thanks for your answer.
John

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by