MATLAB Strings
Lab BA 113 March 16, 1998

This URL is http://www.stewart.cs.sdsu.edu/cs205/module8/index.html

We want to explore MATLAB Strings, which are arrays of characters. We'll need this for Wednesday's exploration of graphics and how to construct titles and labels.

First, let example a MATLAB command you've used - input.

y = input (' Enter anything > ','s')

and enter a number, say 45. Then repeat the command

z = input (' Enter anything > ','s')

and enter a string, say this is a test. To see the effects of this and the size of our new variables, type

whos

Allows you to type any sort of data and have it treated as characters, not as numbers. But then these are not numbers anymore. As you'd probably expect, there is a MATLAB command to convert the string representation of the contents of y (assuming you followed my instructions above and entered the 45).

str2num(y)

Now example the sizes and data types of the variables in our workspace

whos

We want to look at putting strings into aggregate structures. First, just concatenating strings:

h = 'hello';

s = [h ' world']

s0 = [h ' world']'

What is we wanted to list the two words in separate rows of the matrix. Try

s1 = [h; 'world']

s2 = [h;' world']

Notice the NASTY error message you get for s2. This is because you oare storing this data in a matrix, when you use more than one row, and you know that you must have the same number of columns for each row. It's time for another

whos

We can have a padded character array

s = char('A', 'rolling', 'stone', 'gathers', 'momentum.')

Or a cell array, which uses the { notation instead of the [ notation for matrices.

c = {'a';'rolling';'stone';'gathers';'momentum.'}

You can convert between padded character arrays and cell arrays

s3 = cellstr(s)

And it's time to see the sizes and types of our data. How many bytes does a character use?

whos

Let's have some fun with strings

b = 'peter piper picked a peck of pickled peppers'

findstr(b,'p')

strrep (b,'p','P')

s = [h ' world']

s(11:-1:1)

rad = 2.5; area=pi*rad^2;
t = ['A circle of radius ' num2str(rad) ' has an area of ' num2str(area) '.'];
disp(t)
Type the following command and then use your arrow keys to move back to the typed command and change one character to perform the following format investigations
fprintf('%.0e\n',pi)
fprintf('%.1e\n',pi)
fprintf('%.3e\n',pi)
fprintf('%.5e\n',pi)
fprintf('%.10e\n',pi)
fprintf('%.0f\n',pi)
fprintf('%.1f\n',pi)
fprintf('%.3f\n',pi)
fprintf('%.5f\n',pi)
fprintf('%.10f\n',pi)
fprintf('%.12f\n',pi)
fprintf('%.0g\n',pi)
fprintf('%.1g\n',pi)
fprintf('%.3g\n',pi)
fprintf('%.5g\n',pi)
fprintf('%.10g\n',pi)
fprintf('%8.0g\n',pi)
fprintf('%8.1g\n',pi)
fprintf('%8.3g\n',pi)
fprintf('%8.5g\n',pi)
fprintf('%8.10g\n',pi)
An even simple technique is to put all the information we've used today together (along with the num2str command and have a loop do the drudgery for us.
for i=1:5
fprintf(['%8.' int2str(i) 'g\n'],pi)
end