I have a loop
for i = 1: n
f = @(x) x + vec(i)
end
Is it posible to add up all these functions into one single anonymous function??
Thanks.
The best I can suggest is to incrementally add your functions like this:
n = 10;
vec = rand(1,n); % Random data
f = @(x)x + vec(1); % Initial function
for i = 2:n
f = @(x)x + vec(i) + f(x); % Add previous sum to next
end
x = 2;
s = f(x) % Evaluate
If you need to save each function separately and sum afterwards, you can create a cell array of function handles and use cellfun to evaluate all of them for a particular value of x:
n = 10;
vec = rand(1,n); % Random data
f = cell(1,n); % Pre-allocate cell
for i = 1:n
f{i} = @(x)x + vec(i) % Save a handle to each function in cell array
end
x = 2;
s = sum(cellfun(@(c)c(x),f)) % Evaluate each function at x and sum
Another option would be to do this using Symbolic Math, though this may be very inefficient depending on your actual functions:
n = 10;
vec = rand(1,n); % Random data
syms x;
f(x) = x+vec; % Create vector function
x = 2;
s = double(sum(f(x))); % Evaluate and convert to floating point
It's impossible to know what your actual problem is and if any these will work for you without a more detailed question, so you may need to alter them considerably for your particular application.
nelements ofvecshould be increased byx? Or do you wantnseparate functions, each which would increasevec(i)byx. - mpaskovndifferent functions that each adds a different number (pre-defined fromvec) tox. And after you have yournfunction you want to do something with them all simultaneously. - mpaskovf = @(x) n*x + sum(vec)should do the trick for you. Especially since you are not storing(x+1),(x+2), ... in an array. - nahomyaja