简体   繁体   中英

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. So, for each m1(i) and m2(i) I want to have a handle W(i). I need it in order to find those W(i)'s in the next step using fsolve in something looking like this

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

I have tried using arrayfun, but received a following error

   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)

    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.

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. Is this correct? If so you can create a cell-array of the same dimension as m1 with a function handle in each dimension:

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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