Reputation: 41
I have a cell array with size (n,1) that includes a function handle. Every cell has to include specific function handle and the summation of function handles in the previous cells. How can I perform this operation? To clarify this is an illustration.
A = cell(size(ones(n,1)));
for i = 1 : n
A{i,1} = @(x) A{i-1,1} + i .* x;
end
How to get A{n,1}
at x = 2
(for example)
Upvotes: 2
Views: 268
Reputation: 10450
Recalling @gnovice comment, you can also just make a cell array of the handles, and then call a function that sums them up to n
:
N = 10;
A = cell(N,1);
A{1} = @(x) 1.*x;
for k = 2:N
A{k} = @(x) k.*x;
end
% the following function sums the output of A{1}(x) to A{n}(x):
f = @(n,x) sum(cellfun(@(c) c(x),A(1:n)));
The result:
>> f(5,2)
ans =
30
>> f(N,2)
ans =
110
This way, every change of the functions in A
will have an immediate effect upon redefining f
:
>> A{3} = @(x) -x;
>> f = @(n,x) sum(cellfun(@(c) c(x),A(1:n)));
>> f(N,2)
ans =
102
>> f(5,2)
ans =
22
Upvotes: 2
Reputation: 6863
You are actually pretty close, but you need to add a special case for i = 1
and you need to call the function:
n = 10;
A = cell(size(ones(n,1)));
A{1,1} = @(x) 1 .* x;
for ii = 2 : n
A{ii,1} = @(x) A{ii-1,1}(x) + ii .* x;
end
I replaced i
with ii
, to avoid confusion with complex numbers. For the case n = 10
:
>> A{n}(2)
ans =
110
Upvotes: 3