Effacer les filtres
Effacer les filtres

Can I create multiple anonymous functions with a for loop?

5 vues (au cours des 30 derniers jours)
Jarred Grant
Jarred Grant le 5 Nov 2020
Commenté : Jarred Grant le 5 Nov 2020
I am trying to create multiple anonymous functions with a for loop. I am learning how to create my own MATLAB code to create spline interpolating polynomials. I have all of the coefficients that I need and now I just want to have a for loop create all of the anonmyous functions for me so that I can use the switch-case environment to choose the correct polynomial to evaluate a given interpolating point.
a, b, c and d are vectors of the same size and I have already calcluated them. xData is a vector of given x values where we know the corresponding y values. What I have so far is:
for i = 1:length(b)
S(i) = @(x) a(i) + b(i)*(x - xData(i)) + c(i)*(x - xData(i))^2 + d(i)*(x - xData(i))^3
end
I'm sure I have some errors in here as I am new to coding, but I hope the general idea of what I am trying to accomplish is clear. When I try to run this, it gives me an error 'nonscalar arrays of function handles are not allowed; use cell arrays instead'. I have looked up cellfun() and arrayfun(), but I am not sure how I would use them correctly here.

Réponse acceptée

Subhadeep Koley
Subhadeep Koley le 5 Nov 2020
Modifié(e) : Subhadeep Koley le 5 Nov 2020
Hi Jarred, defining 'S' as a cell array should resolve the issue.
% Pre-allocating 'S' as cell array
S = cell(1, length(b));
% Creating anonymous function handles
for idx = 1:length(b)
S{idx} = @(x) a(idx) + b(idx)*(x - xData(idx)) + c(idx)*(x - xData(idx))^2 + d(idx)*(x - xData(idx))^3;
end

Plus de réponses (0)

Catégories

En savoir plus sur Sparse 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