fun is doing odd things

조회 수: 2 (최근 30일)
John Hey
John Hey 2023년 6월 23일
이동: John D'Errico 2023년 6월 23일
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)???

답변 (1개)

VBBV
VBBV 2023년 6월 23일
편집: VBBV 2023년 6월 23일
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
John Hey
John Hey 2023년 6월 23일
이동: John D'Errico 2023년 6월 23일
Dear VBBV,
Many thanks for your answer.
John

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by