MATLAB Answers

amir saeed

Changing function with Iteration

Asked by amir saeed
on 19 Apr 2012

Hi all I want to call function/script iteratively as I made mutants of a program and each mutant ends with a iteration number. The problem is that I need to change function name iteratively with each iteration of matlab code. Please help me out. My sample mutants are ArithOper1(input),ArithOper2(input),ArithOper3(input),........

Thanks you in Advance




No products are associated with this question.

2 Answers

Answer by Matt Tearle
on 19 Apr 2012
 Accepted answer

So you have a bunch of functions called ArithOper1.m, ArithOper2.m, ArithOper3.m, etc? If there's a small enough number of these, you can call the appropriate one using a simple switch construct

switch n
  case 1
     % call ArithOper1
  case 2
     % call ArithOper2

If this is unwieldy, you can use eval:

fnm = ['ArithOper',num2str(n)];
str = ['z = ',fnm,'(x,y);'];    % z = ArithOperN(x,y)


amir saeed
on 19 Apr 2012

Thanks for your prompt response that really works but have a little problem.
I am using the code as below
cd MatlabMutants
cd ..
cd MatlabMutants
for k=1:ilen
% s=['ArithOper' num2str(k)];
% y(k)=eval(s(x))%%s = ['August' int2str(d) '.dat'];
fnm = ['ArithOper',num2str(k)];
str = ['z = ',fnm,'(x);']; % z = ArithOperN(x,y)
cd ..
I have to use the value of computed function. It perform well up to str. On eval(str), it does not return value, as I need this value

Matt Tearle
on 20 Apr 2012

You need to store the output somehow. eval just evaluates a string as a command, so you're executing the command "z = ArithOperN(x);" (with N being filled in with a given value). So you just keep overwriting z in the loop. What do you want to do with the output? Store it somewhere? Just display it? Whatever it is, change your string (str) to make the appropriate command. Equivalently, add some commands after "eval(str)" that does something with the result which is currently stored in z.

Answer by Sean de Wolski
on 19 Apr 2012
  1. FAQ a1 a2 an
  2. doc persistent %use persistent variables
  3. doc switch %make a decision based on something

  1 Comment

amir saeed
on 19 Apr 2012

could not get it. Please ellaborate

Discover MakerZone

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

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!