I would like to use my X(i)s to define my function p, but it says that they are undefined variables or functions. How can I do?
A=[46/15, 5/2, 2/3; 5/2, 8/3, 1; 2/3, 1, 2];
B=[2*exp(1); 2*exp(1); 2*exp(1)-2];
X=linsolve(A,B)
integral(@(x) f(x),0,1)
function p=p(x)
p=X(1)*x.^2+X(2)*x+X(3);
end
function f=f(x)
f=(exp(x)-p(x)).^2;
end

 採用された回答

Star Strider
Star Strider 2021 年 10 月 17 日

0 投票

Try this instead —
function pv=p(X,x)
pv=X(1)*x.^2+X(2)*x+X(3);
end
Here, ‘X’ are the parameters and ‘x’ is the variable. Also, naming the variable inside the function to be the same as the function name confuses MATLAB (and everyone who reads the code).
Beyond that, what the problem and the desired result may be are both not possible to determine, and the parameters ‘X’ are nowhere either defined or calculated, so I’ll stop here.
.

4 件のコメント

Florian Spicher
Florian Spicher 2021 年 10 月 17 日
Thanks for the help. I'm not sure to understand something though. Do you mean that I can't compute what I would like to?
Star Strider
Star Strider 2021 年 10 月 17 日
It is definitely possible to run that code and get results with some changes to the functions, those being to pass the parameter vector to both functions.
Try this —
A=[46/15, 5/2, 2/3; 5/2, 8/3, 1; 2/3, 1, 2];
B=[2*exp(1); 2*exp(1); 2*exp(1)-2];
X=linsolve(A,B)
X = 3×1
0.8451 0.8711 1.0011
integral(@(x) f(X,x),0,1)
ans = 8.3588e-05
function pv=p(X,x)
pv=X(1)*x.^2+X(2)*x+X(3);
end
function f=f(X,x)
f=(exp(x)-p(X,x)).^2;
end
Note — I added the parameter argument ‘X’ to both functions, because ‘f’ needs it in order to pass it to ‘p’. With those changes, it works!
.
Florian Spicher
Florian Spicher 2021 年 10 月 17 日
Oh well yeah, you meant the code I published! Then definitely. I thought you meant "the actual purpose of the program makes no sense".
Thank you again for the help!
Star Strider
Star Strider 2021 年 10 月 17 日
As always, my pleasure!
Since I don’t know the actual purpose of the code, I’m in no position to criticise its application. I’m just happy that I was able to help you get it to run! (I didn’t look carefully at the code the first time, so I didn’t notice that the ‘X’ parameters actually existed, and were calculated from the regression.)
.

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

その他の回答 (0 件)

カテゴリ

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by