Call functions with names generated from strings

63 ビュー (過去 30 日間)
Kristian Jørgensen
Kristian Jørgensen 2013 年 5 月 3 日
I am writing a piece of code for a 2 phase oil and water reservoir simulation. Assume I have a structure called fluid, in which there are several functions for parameteres for each phase, appropriately named:
fluid.muO @(p) %(oil viscosity as a function of pressure)
fluid.muW @(p) %(water viscosity as a function of pressure)
If I want to make a general function in which the phase is an input parameter, how do I use this string to call the function above? I tried:
phase = 'O'
eval = strcat('fluid.mu',phase)
Where to go from here I do not know, but I wish to use the variable phase to call fluid.muO and fluid.muW. Is it even possible?
Cheers

採用された回答

Iman Ansari
Iman Ansari 2013 年 5 月 3 日
Hi.
fluid.muO=@(p) p.^2+1;
fluid.muW=@(p) cos(p)+2*sin(p);
phase = 'O';
name = strcat('fluid.mu',phase);%['fluid.mu',phase]
f=eval(name);
f([0 1 3])
  1 件のコメント
Kristian Jørgensen
Kristian Jørgensen 2013 年 5 月 3 日
Thank you! That worked out perfectly!

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

その他の回答 (1 件)

the cyclist
the cyclist 2013 年 5 月 3 日
Here is one way:
fluid.muO = @(p) p;
fluid.muW = @(p) 2.*p;
phase = 'O';
eval(['F = @(p) fluid.mu',phase,'(p)'])
p = 1:10;
F(p)

カテゴリ

Help Center および File ExchangeWaveform Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by