Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 12 Okt. 2020
Bearbeitet: Ameer Hamza am 12 Okt. 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

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by