Hello, I haven't figured out to find a way to create a new function out of multiplying 2 functions, for example:
fun1 = @(x) sin(x);
fun2 = @(x) cos(x);
*I want to create fun3 out of them so that -*
fun3 = @(x) sin(x)*cos(x)
The reason I'm asking this is that if I define fun3 as-
fun3 = @(x) fun1(x)*fun2(x)
and obviously it doesn't turn into-
fun3=@(x) sin(x)*cos(x)
thus I can't integrate fun3-
integral(fun3,0,5) ~= int(sin(x)*cos(x),x,0,5)
Matlab just says-
Error using *
Inner matrix dimensions must agree.
Thank you

 採用された回答

Star Strider
Star Strider 2017 年 4 月 19 日

5 投票

You need to use element-wise operations here, using the dot (.) operator for element-wise multiplication, (.*).
This works:
fun1 = @(x) sin(x);
fun2 = @(x) cos(x);
fun3 = @(x) fun1(x).*fun2(x);
int_fun3 = integral(fun3, 0, 5)
int_fun3 =
459.7679e-003
See the documentation on Array vs. Matrix Operations for a full discussion.

6 件のコメント

yuval
yuval 2017 年 4 月 19 日
Thanks, didn't realize that was the issue.
Star Strider
Star Strider 2017 年 4 月 19 日
My pleasure.
Many people don’t, and I suspect everyone has encountered the problem themselves at least once. (I have.)
JacobsonRadical
JacobsonRadical 2022 年 4 月 24 日
Great Answer. I've also been confused by this for a while. You saved me!
Star Strider
Star Strider 2022 年 4 月 24 日
Thank you!
Grant Peel
Grant Peel 2024 年 4 月 14 日
Does this method work with 2 dimensional functions:
fun1 = @(x,y) sin(x)*sin(y);
fun2 = @(x,y) xy;
fun3 = @(x,y) fun1(x,y).*fun2(x,y);
integral2(fun3, 0,1,0,1)
Star Strider
Star Strider 2024 年 4 月 14 日
The easiest way to find out is to first fully vectorise the constituent equations, and then try it —
fun1 = @(x,y) sin(x).*sin(y);
fun2 = @(x,y) x.*y;
fun3 = @(x,y) fun1(x,y).*fun2(x,y);
int_fun3 = integral2(fun3, 0,1,0,1)
int_fun3 = 0.0907
It seems that it does!
.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeEncryption / Cryptography についてさらに検索

質問済み:

2017 年 4 月 19 日

コメント済み:

2024 年 4 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by