简体   繁体   English

为向量中的每个元素创建函数句柄(Matlab)

[英]Creating a function handle for each element in a vector (Matlab)

I have a following issue. 我有以下问题。 I am trying to create a function handle, which is a vector. 我试图创建一个函数句柄,它是一个向量。 In particular, I have something like this 特别是我有这样的东西

    EQ0 = @(W) m1.^2*(exp(W))-m2.^2

where m1 and m2 are the vectors of the same dimension. 其中m1和m2是相同维的向量。 So, for each m1(i) and m2(i) I want to have a handle W(i). 因此,对于每个m1(i)和m2(i),我都想拥有一个手柄W(i)。 I need it in order to find those W(i)'s in the next step using fsolve in something looking like this 我需要它以便在下一步中使用fsolve在类似以下的内容中找到那些W(i)

    n=size(m1)        
    x0 = zeros(n);
    Wbar = fsolve(EQ0,x0)

I have tried using arrayfun, but received a following error 我尝试使用arrayfun,但收到以下错误

   EQ0 = arrayfun( @(W) m1.^2*(exp(W))-m2.^2, m1=m1e, m2=m2e)
   Error: The expression to the left of the equals sign is not a valid target for an assignment.

Another attempt in using arrayfun resulted in this (here I just used m1 and m2 vectors directly, not as an inputs like in previous case) 使用arrayfun的另一种尝试导致了这种情况(这里我只是直接使用m1和m2向量,而不是像以前的情况那样作为输入)

    EQ0 = arrayfun( @(W) m1.^2*(exp(W))-m2.^2,:)
    Undefined variable arrayfun.

I am clearly missing something. 我显然缺少了一些东西。 I have looked on some feeds on arrayfun but it looks like my problem is somewhat different. 我在arrayfun上查看了一些提要,但看来我的问题有所不同。

Any advice is appreciated. 任何建议表示赞赏。

So if I understood you right you want to have for each m1(i) or m2(i) a seperate function handle EQ0(i) which can operate with an vector W in the following way EQ0(i) = @(W) m1(i)^2*(exp(W))-m2(i)^2. 因此,如果我理解正确,那么您希望为每个m1(i)或m2(i)拥有一个单独的函数句柄EQ0(i),该函数句柄可以通过以下方式与向量W一起操作EQ0(i)= @(W)m1 (i)^ 2 *(exp(W))-m2(i)^ 2。 Is this correct? 这个对吗? If so you can create a cell-array of the same dimension as m1 with a function handle in each dimension: 如果是这样,您可以创建一个与m1维度相同的元胞数组,并在每个维度中具有一个函数句柄:

EQ0 = cell(size(m1));
for ii = 1:numel(m1)
   EQ0(ii) = {@(W) m1(ii)^2*exp(W)-m2(ii)^2};
end

EDIT: Another option could be: 编辑:另一个选项可能是:

EQ0 = @(W)arrayfun(@(Wel,m1el,m2el)m1el^2*exp(Wel)-m2el^2,W,m1,m2);
fsolve(EQ0, W_Values)

Here m1, m2 should be defined beforehand. 在此应预先定义m1,m2。 Otherwise you have to add them as arguments of the first anonymous function. 否则,您必须将它们添加为第一个匿名函数的参数。 So by calling arrayfun(@(Wel, m1el, m2el)..., W, m1, m2) you do your elementwise calculations for the entries in W, m1, m2 defined by the anonymous function handle you have passed in the first argument of arrayfun. 因此,通过调用arrayfun(@(Wel, m1el, m2el)..., W, m1, m2)您可以对您在第一个参数中传递的匿名函数句柄定义的W, m1, m2的条目进行元素计算arrayfun。 But since you want to define your W differently each time, you make an anonymous function of that arrayfun command, which takes W as an argument. 但是由于您每次都想以不同的方式定义W ,因此您要为该arrayfun命令创建一个匿名函数,该函数将W作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM