Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
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?

Réponse acceptée

Ameer Hamza
Ameer Hamza le 12 Oct 2020
Modifié(e) : Ameer Hamza le 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

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by