numArrays = 10;
A = cell(numArrays,1);
for n = 1:numArrays
A{n} = magic(n);
end
Access the data in the cell array by indexing with curly braces. For example, display the
fifth element of A:
A{5}
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
The assignment statement A{n} = magic(n) is more elegant and efficient than this call
to eval:
eval(['A', int2str(n),' = magic(n)']) % Not recommended
For more information, see:
- “Create Cell Array” on page 12-3
- “Create Structure Array” on page 11-2
Files with Sequential Names
Related data files often have a common root name with an integer index, such as
myfile1.mat through myfileN.mat. A common (but not recommended) use of the eval
function is to construct and pass each file name to a function using command syntax, such
as
eval(['save myfile',int2str(n),'.mat']) % Not recommended
The best practice is to use function syntax, which allows you to pass variables as inputs.
For example:
currentFile = 'myfile1.mat';
save(currentFile)
2 Program Components