MATLAB Answers

Can I create multiple anonymous functions with a for loop?

3 views (last 30 days)
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.

  0 Comments

Sign in to comment.

Accepted Answer

Subhadeep Koley
Subhadeep Koley on 5 Nov 2020
Edited: Subhadeep Koley on 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

More Answers (0)

Community Treasure Hunt

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

Start Hunting!