1

I'd like to dynamically construct a function that can then be referred to with a function handle for later use in Matlab functions such as integral(fun,a,b).

As an example imagine a function with terms:

(x-A)/(D-A) * (x-B)/(D-B) * (x-C)/(D-C)

where x is a variable and A,B,C,D are constants from a vector (call it K=[A,B,C,D]' as an example) generated by a different function.

I could do:

fun = @(x) (x-A)/(D-A) * (x-B)/(D-B) * (x-C)/(D-C)

However, this restricts me to three terms. I'd like to be able to take an arbitrary length vector of constants and generate a function of similar form to the one above. Normally this is easy in Matlab, but it seems like function handles expect 'x' to be a scalar, so something like:

prod( (x - K(1:3)) ./ K(4)-K(1:3) )

returns an error.

4

1 回答 1

1

这不是真的

函数句柄期望 'x' 是一个标量

问题不在于函数句柄,也不是函数是anonymous的事实。问题只是您用来定义该功能的操作:您不能这样做

prod( (x - K(1:3)) ./ K(4)-K(1:3) )

xK都是任意大小的向量时。作为旁注,分母中缺少一对括号。

你想要的(如果我理解正确的话)可以用bsxfun两次来完成。假设xK都是向量,使用

prod(bsxfun(@rdivide, bsxfun(@minus, x.', K(1:end-1)), K(end)-K(1:end-1)))

计算你的函数。

所以:首先定义K,然后您可以将匿名函数及其句柄定义为

fun = @(x) prod(bsxfun(@rdivide,bsxfun(@minus,x.',K(1:end-1)),K(end)-K(1:end-1)))

请注意,K当您定义匿名函数时,它的值是“硬连线”到匿名函数中的。如果您稍后修改,该功能不会改变K(当然,除非您使用 new 再次定义该功能K)。

例子:

>> K = [3 4 5 6].';
>> fun = @(x)prod(bsxfun(@rdivide,bsxfun(@minus,x.',K(1:end-1)),K(end)-K(1:end-1)));
>> x = [1 2].';
>> fun(x)
ans =
    -4    -1

查看:

>> prod( (x(1) - K(1:3)) ./ (K(4)-K(1:3)) )
ans =
    -4

>> prod( (x(2) - K(1:3)) ./ (K(4)-K(1:3)) )
ans =
    -1
于 2014-09-08T22:51:05.213 回答