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

2 次查看(过去 30 天)
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
Ameer Hamza 2020-10-12
编辑:Ameer Hamza 2020-10-12
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by