gpt4 book ai didi

algorithm - MATLAB 函数可以将数学函数作为输入吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:19:02 24 4
gpt4 key购买 nike

我是这个站点和 MATLAB 的新手,所以如果我的问题很幼稚或与某些已经存在的问题重复,请原谅。

好吧,我是一名数学专业的学生,​​使用 MATLAB 来帮助我的项目。有一个叫做“L^2 内积”的东西,你需要 2 个数学函数,如 f(x) 和 g(x) 作为输入。它应该像

inner(f,g)=integrat f(x)*g(x) from 0 to 1.

问题是我不知道如何在 MATLAB 中编写它。

总而言之,我想制作一个 MATLAB 函数,其输入是两个数学函数,输出是一个实数。我知道如何制作内联对象,但我不知道如何继续。任何帮助将不胜感激。

附言。我不知道我的标签是否合适或是否符合主题,请耐心等待。

最佳答案

我将在@transversality 条件的基础上更详细地编写(例如,应该有一个.*)

匿名函数示例

h = @sin % This assigns h the function handle of the sin function
% If you know c, c++, this is basically a function pointer

inner = @(f,g)integral(@(x)f(x).*g(x),0,1) % This assigns the variable inner
% the function hanlde of a function which
% takes in two function handles f and g
% and calculates the integral from 0 to 1
% Because of how Matlab works, you want .* here;
% you need f and g to be fine with vector inputs.

inner(h, @cos) %this will calculate $\int_0^1 sin(x)cos(x)dx$

这产生 0.354

将 inner 写成常规函数

在前面的示例中,inner 是一个变量,变量的值是计算内积的函数的函数句柄。您也可以只编写一个计算内积的函数。使用以下代码创建文件 myinner.m:

function y = myinner(f, g)
y = integral(@(x)f(x).*g(x),0,1);

然后你可以用同样的方式调用 myinner:

myinner(@sin, @cos)

结果:0.354

另请注意,integral 函数以数值方式计算积分,在奇怪的情况下,可能会出现数值问题。

关于algorithm - MATLAB 函数可以将数学函数作为输入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36491034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com