Getting Started |
Passing String Arguments to Functions
You can write MATLAB functions that accept string arguments without the parentheses and quotes. That is, MATLAB interprets
However, when using the unquoted form, MATLAB cannot return output arguments. For example,
creates a legend on a plot using the strings apples
and oranges
as labels. If you want the legend
command to return its output arguments, then you must use the quoted form.
In addition, you cannot use the unquoted form if any of the arguments is not a string.
Constructing String Arguments in Code
The quoted form enables you to construct string arguments within the code. The following example processes multiple data files, August1.dat
, August2.dat
, and so on. It uses the function int2str
, which converts an integer to a character, to build the filename.
for d = 1:31 s = ['August' int2str(d) '.dat']; load(s) % Code to process the contents of the d-th file end
A Cautionary Note
While the unquoted syntax is convenient, it can be used incorrectly without causing MATLAB to generate an error. For example, given a matrix A
,
The eig
command returns the eigenvalues of A
.
The following statement is not allowed because A
is not a string; however, MATLAB does not generate an error.
MATLAB actually takes the eigenvalues of ASCII numeric equivalent of the letter A (which is the number 65).
Global Variables | The eval Function |