简体   繁体   中英

Add terms to anonymous function in for loop

I am trying to add terms to an anonymous function in a for loop.

Isotherm = @(N) log(N)-log(P);

k=0; for an=a Isotherm2 = @(N) (1/T)*an*mpower(N,k); Isotherm = @(N) Isotherm(N) + Isotherm2(N); k=k+1; end

k=0; for bn=b Isotherm2 = @(N) bn*mpower(N,k); Isotherm = @(N) Isotherm(N) + Isotherm2(N); k=k+1; end

I've tried the preceding code, but it is not working correctly. Do I need to use an m-file function?

It's a little hard to follow what you are intending to do. However, if N is a scalar value, the following vectorized solution should perform the computation you want:

Isotherm = @(N) log(N)-log(P) + ...
                (1/T)*sum(a.*N.^(0:numel(a)-1)) + ...
                sum(b.*N.^(0:numel(b)-1));

Incidentally, as much as I DID NOT expect the following to work, it actually does:

>> f = @(x) x;
>> for i = 2:4, f = @(x) f(x) + x.^i; end    %# f(x) = x + x.^2 + x.^3 + x.^4
>> f(2)

ans =

    30    %# 2 + 4 + 8 + 16

>> f(3)

ans =

   120    %# 3 + 9 + 27 + 81

So the way you are adding your anonymous functions may not be the source of your problem, although it is a very confusing way to do things and may have some other limitations I have yet to find.

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