Page 93 - Basics of MATLAB and Beyond
P. 93
>> eval(str)
v =
1 2 3 4 5
The eval(str) statement acts just as if we had typed v = 1:5 at the
command line. To suppress the output we need to add a semicolon
character to the end of the string:
>> str = ’v = 1:5;’
str =
v = 1:5;
>> eval(str)
The eval command now produces no output, while still defining the
variable v. To take another example, let us suppose we want to define a
set of vectors v i =1, 2,...i for i =1, 2 ... 10. At the command line we
could type:
v1=1;
v2 = 1:2;
v3= 1:3;
and so on. The eval command provides a neat solution:
>> clear
>> for i = 1:10
str = [’v’ int2str(i) ’ = 1:i;’];
eval(str)
end
This has generated the variables v1, ... , v10, with the appropriate ele-
ments:
>> whos
Name Size Bytes Class
i 1x1 8 double array
str 1x10 20 char array
v1 1x1 8 double array
v10 1x10 80 double array
v2 1x2 16 double array
v31x3 24 double array
v4 1x4 32 double array
v5 1x5 40 double array
v6 1x6 48 double array
v7 1x7 56 double array
v8 1x8 64 double array
v9 1x9 72 double array
Grand total is 66 elements using 468 bytes
c 2000 by CRC Press LLC