Calling functions that have a variable name

11 ビュー (過去 30 日間)
Daniel Cohen
Daniel Cohen 2023 年 10 月 27 日
コメント済み: Daniel Cohen 2023 年 10 月 29 日
I have a set of functions that have the general naming scheme of: function%d_%d. They all have the same input and I want to call them within two loops (for example a loop for variable n and another for k, meaning calling for functionn_k). Is it possible to do so and how?
  3 件のコメント
Stephen23
Stephen23 2023 年 10 月 29 日
"...the generated functions are named (essentially as) functionn_k."
How exactly? Are you writing them as function files (Mfiles) or as variables in the workspace or something else?
Daniel Cohen
Daniel Cohen 2023 年 10 月 29 日
I have a function that produces using MATLAB symbolic the potential function of some gravitational field. This potential can be addressed based on the order of the potential field (Look up the geopotential model in wiki, I am addressing here for example the J2 J3... fields).
And so, by having a function that computes the field potential symbolicly, I can have the function matlabFunction convert it into actual MATLAB function that are saved as Mfiles.

サインインしてコメントする。

採用された回答

Matt J
Matt J 2023 年 10 月 27 日
編集済み: Matt J 2023 年 10 月 27 日
Just generate handles to all the functions. Then they can be used freely to make function calls, e.g.,
F=cellfun(@str2func, compose('function%d_%d',(1:3)',1:5), 'uni',0)
F = 3×5 cell array
{@function1_1} {@function1_2} {@function1_3} {@function1_4} {@function1_5} {@function2_1} {@function2_2} {@function2_3} {@function2_4} {@function2_5} {@function3_1} {@function3_2} {@function3_3} {@function3_4} {@function3_5}
for i=2,
for j=3,
y=F{i,j}(5)
end
end
y = 50
function y=function2_3(x)
y=10*x;
end
  2 件のコメント
Walter Roberson
Walter Roberson 2023 年 10 月 27 日
str2func is probably the best approach for this.
You could also use feval but it would not be as efficient.
Daniel Cohen
Daniel Cohen 2023 年 10 月 29 日
Thank you, str2func is exactly the solution I was looking for!

サインインしてコメントする。

その他の回答 (1 件)

Catalytic
Catalytic 2023 年 10 月 27 日
移動済み: Image Analyst 2023 年 10 月 28 日
That sounds like a bad idea. You should probably make a single function where (n,k) are one of the arguments -
function oneFunction(n,k,other_arguments)
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by