フィルターのクリア

Can I create multiple anonymous functions with a for loop?

5 ビュー (過去 30 日間)
Jarred Grant
Jarred Grant 2020 年 11 月 5 日
コメント済み: Jarred Grant 2020 年 11 月 5 日
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 Center および File ExchangeSparse Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by