MATLAB Answers


Call functions with names generated from strings

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('',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?




No products are associated with this question.

2 Answers

Answer by Iman Ansari
on 3 May 2013
 Accepted answer


fluid.muO=@(p) p.^2+1;
fluid.muW=@(p) cos(p)+2*sin(p);
phase = 'O';
name = strcat('',phase);%['',phase]
f([0 1 3])

  1 Comment

Thank you! That worked out perfectly!

Answer by the cyclist
on 3 May 2013

Here is one way:

fluid.muO = @(p) p;
fluid.muW = @(p) 2.*p;
phase = 'O';
eval(['F = @(p)',phase,'(p)'])
p = 1:10;


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!