# Array indices must be positive integers or logical values error when using cell arrays

1 view (last 30 days)
Aleem Andrew on 12 Oct 2020
Commented: Ameer Hamza on 12 Oct 2020
The following code is supposed to add a function of x to a function handle f whose coefficients depend on the entries of a cell array a.
a = {{'P',8,0},{'l',-8,0,4},{'P',40,4},{'P',6,-16}}
x = linspace(0,6);
f = @(x) 0;
f= f(x) + a{1}{2}*x.^7
for i = 1:numel(a)
if a{i}{1} == 'P'
f = f(x) + a{i}{2}*x;
end
end
There are no problems in doing this when a polynomial is added outside the for loop but the error message is displayed because of the polynomial a{i}{2}*x which is included in the for loop.
Does anyone have suggestions on how to fix this issue?

Ameer Hamza on 12 Oct 2020
Edited: Ameer Hamza on 12 Oct 2020
You are overwriting the function handle f. Change the name of variable in which you are storing the sum.
a = {{'P',8,0},{'l',-8,0,4},{'P',40,4},{'P',6,-16}}
x = linspace(0,6);
f = @(x) 0;
f_ = f(x) + a{1}{2}*x.^7
for i = 1:numel(a)
if a{i}{1} == 'P'
f_ = f(x) + a{i}{2}*x;
end
end
##### 2 CommentsShow 1 older commentHide 1 older comment
Ameer Hamza on 12 Oct 2020
I am glad to be of help!