MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

You can construct file names within a loop using the sprintf function (which is usually
more efficient than int2str), and then call the save function without eval. This code
creates 10 files in the current folder:


numFiles = 10;
for n = 1:numFiles
randomData = rand(n);
currentFile = sprintf('myfile%d.mat',n);
save(currentFile,'randomData')
end


For more information, see:



  • “Command vs. Function Syntax” on page 1-9

  • “Import or Export a Sequence of Files”


Function Names in Variables


A common use of eval is to execute a function when the name of the function is in a
variable character vector. There are two ways to evaluate functions from variables that
are more efficient than using eval:



  • Create function handles with the @ symbol or with the str2func function. For
    example, run a function from a list stored in a cell array:


examples = {@odedemo,@sunspots,@fitdemo};
n = input('Select an example (1, 2, or 3): ');
examples{n}()


  • Use the feval function. For example, call a plot function (such as plot, bar, or pie)
    with data that you specify at run time:


plotFunction = input('Specify a plotting function: ','s');
data = input('Enter data to plot: ');
feval(plotFunction,data)

Field Names in Variables


Access data in a structure with a variable field name by enclosing the expression for the
field in parentheses. For example:


myData.height = [67, 72, 58];
myData.weight = [140, 205, 90];


Alternatives to the eval Function
Free download pdf