Can I create multiple anonymous functions with a for loop?

5 次查看(过去 30 天)
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.

采纳的回答

Subhadeep Koley
Subhadeep Koley 2020-11-5
编辑:Subhadeep Koley 2020-11-5
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by