Next: Sparse Matrices Up: Further MATLAB Previous: Polynomials

Text

Text strings are given in single quotes, e.g. 'a test string'. A string is a row vector of characters.

.1ex>> s = 'a string';
.1ex>> s(5)
ans =
r Normal vector manipulation carries over into strings; resultant vectors will frequently be of numbers, especially if the manipulation wouldn't make sense as a string. This is done with normal ASCII converson. Both real(vector) and abs(vector) force ASCII decimal representation, while setstr(vector) forces character representation if possible. You can use isstr to test whether a vector is a string. (And isletter and isspace to test individual characters.)

.1ex>> s - 1
ans =

.1ex>> [s ' which is longer than it was']
ans =
a string which is longer than it was

The help strfun entry gives a nice summary of string functions.

A string (like anything else) can be displayed with disp; this can be useful in M-files. Prompted input is available with input. In the form input('give me an answer: '), it prints its string argument without a carriage return and waits for the user to respond; the response is evaluated in the workspace and the result returned. In the form input('give me an answer: ', 's'), the response is not evaluated, but is returned as a literal string. Advanced prompted input is available with menu, and beyond that with uimenu and uicontrol.

To execute a string as a MATLAB expression, use eval. Given a single string argument, it attempts to evaluate it as if it had been entered in the current workspace. The results are returned in a vector. If eval is given a second string argument, and the execution of the first generates an error, it will attempt to evaluate the second.

The function error takes a single string argument, displays it, and exits from any m-file it occurs within (unless the argument is an empty string, in which case nothing happens).

The last error message generated is recalled by lasterr. It is reset to an empty string by lasterr(''). It is most often used when giving eval two arguments, as the second can examine its contents to see how the first failed.

There are a number of other useful string functions. Case conversion is done by upper and lower. Sequences of spaces are generated by blanks (the transpose then acts as a sequence of newlines), and trailing spaces are removed by deblank. Comparison is done with strcmp, searching with findstr, search and replace with strrep, and parsing by delimiters with strtok.

Conversions between strings and integer, real, and hex representations of numbers are available with num2str, int2str, str2num, hex2num, hex2dec, and dec2hex. Matrix conversations are handled by str2mat and mat2str. For more general conversions, see help for sprintf and sscanf; for use with files see help for fprintf and fscanf.

Next: Sparse Matrices Up: Further MATLAB Previous: Polynomials

sepherke
Sat Mar 21 21:42:28 EST 1998