Can I create multiple anonymous functions with a for loop?

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개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2020년 11월 5일

댓글:

2020년 11월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by