0
votes

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.

1
I am not sure that the function makes sense at all, can you try to explain what it is that you would like to sum? The first n elements of vec should be increased by x? Or do you want n separate functions, each which would increase vec(i) by x. - mpaskov
so at every loop the function is x + 1, x + 4, x + 3, x + 56, What I would like is a function that is (x+1) + (x+4) + (x+3) + (x+56) +... - user3532764
So you want n different functions that each adds a different number (pre-defined from vec) to x. And after you have your n function you want to do something with them all simultaneously. - mpaskov
Correct. Specifically I would like to add them all up to define a new anonymous function. - user3532764
f = @(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

1 Answers

0
votes

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.