Chapter 2:  Strings and Vectors

 

str1 = 'this is all new to me'

str2='I have no clue what I am doing'  

 

str1 =

this is all new to me

str2 =

I have no clue what I am doing  

 

You just told Matlab to create two strings of letters 'I have no idea what I’m doing' and to name those strings str1 and str2.

 

The single quotes tell Matlab that str1 is a string of letters (not numbers, more on that later). A string that only contains a single letter is generally called a character or char.

 

What is a variable?

 

str1 and str2 are both variables

 

A variable is a generic term that is used to describe a piece of information. This information can be a character (a single letter), a string (a string of characters), a double (a single number,), a vector (a list of numbers), or a matrix (a two or more dimensional set of numbers), as well as some other funky things you'll learn about.

 

Finding out what variables you have: who, whos, and disp

 

The who command asks your computer to give you a list of all the variables you have in memory. At the moment the only variables you have are str1 and str2

 

who

 

 

Your variables are:

 

str1  str2    

 

The command whos gives you a little more information about those variables.

 

whos

 

  Name      Size            Bytes  Class    Attributes

 

  str1      1x21               42  char              

  str2      1x30               60  char                 

 

As well as the name of each variable, whos tells you how long a list it is (second column), how much computer memory (Bytes) the list uses (third column, more on that later) and whether it is a list of letters (char) or numbers (double). We'll get into more technical detail about exactly what a double is later on. For now, just think of it as a number.

 

Typing the name of a variable without a semicolon asks your computer to tell you what is contained within that variable. 

 

str1  

 

str1 =

this is all new to me  

 

str3='is it all going to be this boring?'  

 

str3 =

is it all going to be this boring?  

 

Compare the commands above, with the one below, where we add a semi-colon at the end.

 

str1;

 

str3='is it all going to be this boring?';  

 

The semi-colon tells Matlab that you don't want it to display the output of each command. The technical expression is that the semi-colon "suppresses" output to the command window.

 

Using disp also displays what a variable is, but in a slightly more concise form, where the command window only shows the contents instead of also repeating the name of the variable

 

disp(str1)

 

this is all new to me  

 

Creating an m-file

 

Make sure the command window is at the front. Now go to the menu bar and choose File->New->M-file.  

You’ll see a blank document in a new editor window.

Every program begins with a few lines of documentation. This is called a header. Good headers contain the following information

The name of the program

A description of what it does

Who wrote it, and when

 

% StringsAndVectors.m

%

% this program provides examples of ways that you can create and index strings

% and vectors

%

% written by IF 3/2007  

Make sure every new line begins with a %  . The %   tells Matlab to ignore that line – these comments aren’t for Matlab, they’re for you. Commented text will probably show up as being green.

Headers are important. You may think that you will remember the programs you write – but trust me, you won’t! Getting in the habit of having good up-to-date headers is like cleaning your teeth – it’s boring but it will save you a lot of pain in the long run.

Now create a folder somewhere on your computer called LearningMatlab (or something like that). Don’t put it inside the Matlab program folder since anything inside that folder is liable to be deleted if you do a major upgrade of Matlab.

 

Don't let the name of this folder have any '/' symbols or spaces or funny characters in it since Matlab doesn't like that (the same is true of the titles of m-files- Strings&Vectors.m is a name Matlab won’t like at all.).

 

Save the new m-file as StringsAndVectors.m inside your LearningMatlab folder.

 

Setting the path 

 

Now type:

 

help StringsandVectors  

 

 

StringsandVectors not found.

 

Use the Help browser Search tab to search the documentation, or

type "help help" for help command options, such as help for methods.  

 

You will almost certainly get the error message MakingMatrices not found.

 

When Matlab says that a file is “not found” that means Matlab can’t find an m-file that has that particular name. Sometimes the reason you can’t find a file is that it doesn’t exist (e.g. you’ve got a typo in the name. The other reason Matlab can’t find your new file is because Matlab is only allowed to look for files in certain places.

 

One place that Matlab always looks for files is the current directory or working directory. In fact this is the first place that Matlab looks. When you start Matlab it automatically links to a particular folder (the default setting is made by Matlab). If you don’t tell it otherwise it will save files to that folder. You can see what folder Matlab thinks is the current directory using the print working directory command pwd:

 

pwd  

 

ans =

C:\Program Files\MATLAB\R2008a  

 

The other places that Matlab can find files are in folders that are in Matlab’s search path. This path is a simply a list of folders that Matlab is allowed to look in whenever it is trying to find a file. Again Matlab comes with a default set of paths. You can get a list of the current folders in the pathvery easily:

 

path

 

 

     MATLABPATH

 

 

  C:\Documents and toolbox\emlcoder\emlcoder

  C:\Program Files\MATLAB\R2007b\toolbox\emlcoder\emlcodermex

  C:\Program Files\MATLAB\R2007b\toolbox\exlink

  C:\Program Files\MATLAB\R2007b\toolbox\filterdesign\filterdesign

  C:\Program Files\MATLAB\R2007b\toolbox\filterdesign\quantization

  C:\Program Files\MATLAB\R2007b\toolbox\filterdesign\filtdesdemos

  C:\Program Files\MATLAB\R2007b\toolbox\finance\finance

  C:\Program Files\MATLAB\R2007b\toolbox\finance\calendar

  C:\Program Files\MATLAB\R2007b\toolbox\finance\findemos

  C:\Program Files\MATLAB\R2007b\toolbox\finance\finsupport

  C:\Program Files\MATLAB\R2007b\toolbox\finance\ftseries

  C:\Program Files\MATLAB\R2007b\toolbox\finance\ftsdemos

  C:\Program Files\MATLAB\R2007b\toolbox\finance\ftsdata

  C:\Program Files\MATLAB\R2007b\toolbox\finance\ftstutorials

 

We need to add your new folder LearningMatlab to the path. Matlab Make sure the command window is at the front, and go to: File->Set Path in the menu bar. A pop-up window will appear Choose Add With Subfolders, choose your LearningMatlab folder, and click OK. Then choose Save and Close.

 

help MakingMatrices 

 

 

MakingMatrices not found.

 

Use the Help browser Search tab to search the documentation, or

type "help help" for help command options, such as help for methods.  

 

Matlab should be able to find StringsAndVectors.m now. Working with a m-file is nice because you can use a sensible editor rather than having to type each line in full.

 

 

Redefining variables, indexing and subscripting

 

Now we are going to re-define str1 and make it represent a slightly different list of letters

 

str1='I still have absolutely no clue what I am doing';

 

str1  

 

str1 =

I still have absolutely no clue what I am doing  

 

Now imagine we are trying to find out what the third letter in str1 was.We would do this as follows:

 

str1(3)

 

str1(6)  

 

ans =

s

ans =

l  

 

 

The value 3 is called the subscript or the index into str1. With a 1-D string or matrix there is no difference between an index and a subscript so we'll discuss the difference between these two terms a little later. You can see from these examples that Matlab is counting spaces.

 

Now let's create a new variable called mixstr and tell Matlab to make mixstr the same as str1

 

mixstr=str1;

 

mixstr

 

str1  

 

mixstr =

I still have absolutely no clue what I am doing

str1 =

I still have absolutely no clue what I am doing  

 

See, mixstr and str1 are exactly the same. Now let's make the 6th letter in mixstr a 'r'

 

mixstr(6)='r';

 

mixstr  

 

mixstr =

I stirl have absolutely no clue what I am doing  

 

Now let's tell Matlab to make the third letter in mixstr the same as the first letter in str1

 

mixstr(3)=str1(1);

 

mixstr  

 

mixstr =

I Itirl have absolutely no clue what I am doing  

 

Now let's make the first letter in mixstr the same as the third letter in str1

 

mixstr(1)=str1(3);

 

mixstr  

 

mixstr =

s Itirl have absolutely no clue what I am doing  

 

Vectors

 

You can also create lists of numbers. These are called vectors (or sometimes arrays). Here’s four different ways of creating a vector list that goes from two to nine in steps of one.

 

 

vect1=[2 3 4 5 6 7 8 9]  

 

vect1 =

     2     3     4     5     6     7     8     9  

 

vect2=linspace(2, 9, 8)  

 

vect2 =

     2     3     4     5     6     7     8     9  

 

vect3=2:1:9  

 

vect3 =

     2     3     4     5     6     7     8     9  

 

vect4=2:9  

 

vect4 =

     2     3     4     5     6     7     8     9  

 

So in the first example the square brackets tell Matlab that you are creating a single vector (list of numbers).

 

In the second example, you are using a command linspace which has three arguments. The first argument (2) gives you the first value in the vector, the second argument (9) gives you the last value in the vector, and the third argument (8) specifies that you want the list of 8 numbers that are evenly spaced between 2 and 9. You can imagine that this command would be useful if you had collected eight pieces of data at time points evenly spaced between two and nine seconds.

 

In the third example you are asking for a list of numbers that goes from 2 to 9 with a step-size between each number of 1. You can imagine that this command would be useful if you collected a piece of data every second, starting after two seconds and continued collecting that data until nine seconds had gone by.

 

In the fourth example we are using the fact that Matlab assumes a default step-size of 1, so we are simply skipping that part of defining the vector.

 

Here are three ways of creating a list of numbers that goes from 1 to 17 in steps of two.

 

vect5=[1 3 5 7 9 11 13 15 17]  

 

vect5 =

     1     3     5     7     9    11    13    15    17  

 

vect6=linspace(1, 17, 9)  

 

vect6 =

     1     3     5     7     9    11    13    15    17  

 

vect7=1:2:17 

 

vect7 =

     1     3     5     7     9    11    13    15    17  

 

Here are some other examples of how to create vectors.

 

vect8=3:1.5:9  

 

vect8 =

    3.0000    4.5000    6.0000    7.5000    9.0000  

 

vect9=9:-1:-3  

 

vect9 =

     9     8     7     6     5     4     3     2     1     0    -1    -2    -3  

 

vect10=linspace(2, 8, 12)  

 

vect10 =

  Columns 1 through 10

    2.0000    2.5455    3.0909    3.6364    4.1818    4.7273    5.2727    5.8182    6.3636    6.9091

  Columns 11 through 12

    7.4545    8.0000  

 

vect11=linspace(8, 2, 12)  

 

vect11 =

  Columns 1 through 10

    8.0000    7.4545    6.9091    6.3636    5.8182    5.2727    4.7273    4.1818    3.6364    3.0909

  Columns 11 through 12

    2.5455    2.0000  

 

Back to indexing

 

You can index vectors as well as strings. Here we are going to index the second integer in vect3

 

vect3(2)  

 

ans =

     3  

 

You can also index more than one number in a vector or string. Or even use a vector as an index into a string. This is an important thing to understand so make sure you understand the examples below and the exercises at the end of the chapter.

 

vect4(2:1:4)  

 

ans =

     3     4     5  

 

str1(13:23)  

 

ans =

 absolutely  

 

str1(vect1)  

 

ans =

 still h  

 

 

What is an argument?

An argument is the term that is used to describe the value or values that are supplied to a procedure (procedures are also known as commands or functions, more on that later).

 

What is the difference between an array and a vector?

 Technically, in Matlab there are only vectors so the terms tend to be used interchangeably. In some other languages there is a difference: the size of a vector can change but the size of an array is fixed.

 

 

BUG BOX - Index exceeds matrix dimensions

 

x=3:12

 

y=x(11)  

 

x =

     3     4     5     6     7     8     9    10    11    12

??? Index exceeds matrix dimensions.  

 

This is an error message that you will see on a regular basis. It means you are trying to index a value in x that doesn't exist. In this case it doesn't exist because x only has 10 numbers in it and you are asking for the eleventh number in x.

 

 

BUG BOX – Subscript indices must either be real positive integers or logicals

x=-3:20

y=1:2:15  

 

x =

  Columns 1 through 17

    -3    -2    -1     0     1     2     3     4     5     6     7     8     9    10    11    12    13

  Columns 18 through 24

    14    15    16    17    18    19    20

y =

     1     3     5     7     9    11    13    15  

 

x(y) 

 

ans =

    -3    -1     1     3     5     7     9    11  

 

y(x) 

 

??? Subscript indices must either be real positive integers or logicals.  

 

Why does x(y) work while y(x) doesn't? Because x contains negative values you can't use it as an index. It doesn't make sense to ask for the -3rd  or the -1th value of y.

x(3.5)  

 

??? Subscript indices must either be real positive integers or logicals.  

 

 

Here's another example of how you can get the same error – again it doesn't make sense to ask for the 3½th value of x.

 

 

 

 

Clear

Finally I'm going to teach you how to clear all your variables out of memory and start with a fresh slate. Here we are going to use who to see what's in your workspace, and then we will get rid of the single variable x.

 

who  

 

 

Your variables are:

 

ans     str1    str3    vect10  vect2   vect4   vect6   vect8   x      

mixstr  str2    vect1   vect11  vect3   vect5   vect7   vect9   y         

 

clear x

who  

 

 

Your variables are:

 

ans     str1    str3    vect10  vect2   vect4   vect6   vect8   y      

mixstr  str2    vect1   vect11  vect3   vect5   vect7   vect9     

 

x should be gone. Another way of seeing whether a variable still exists is simply to type it's name into the command window.

x  

 

??? Undefined function or variable 'x'.  

 

This error means that x no longer exists. In this case the error message is a good thing since it showed that clear worked.

To clear everything you use clear all

 

who  

 

 

Your variables are:

 

ans     str1    str3    vect10  vect2   vect4   vect6   vect8   y      

mixstr  str2    vect1   vect11  vect3   vect5   vect7   vect9     

 

clear all

who


  

BUG BOX – Undefined function or variable 'stimInterval'

This error means that Matlab is looking for a variable or a function that it can't find. Often this is because of one of the following three issues:

(1) stimInterval is a variable that hasn't been defined yet. Sometimes finding this bug is harder then you might expect because stimInterval was defined at some point when you were writing the code, and then sat in memory after that little piece of code disappeared. So the code ran ok for a while, until you cleared the variables in memory, and then whoops! suddenly there's a problem.

(2) This is a similar issue - a typo in your code. For example you might define a variable stimInterval and then refer to it as stiminterval later in the code.

(3) You are trying to do a calculation on stimInterval but you've been moving code around, so stimInterval is actually defined later in the code then the place you are tying to use it. 

(4) You are actually trying to refer to a function stimInterval and you have a typo. For example, you might refer to the function as stimInterval when you are calling it, but the actual name of the function is stiminterval.

(5) You are refering to a function, but that function is no longer in the path for some reason. So as far as Matlab is concerned that function doesn't exist. The solution to this is to fix your path. 

 

 

Exercises for Chapter 2

 

1. Create the following vectors using both linspace and the : technique

x1=4:3.5:40

x2=40:-2.5:-3

x3=2:2:20  

 

x1 =

  Columns 1 through 10

    4.0000    7.5000   11.0000   14.5000   18.0000   21.5000   25.0000   28.5000   32.0000   35.5000

  Column 11

   39.0000

x2 =

  Columns 1 through 10

   40.0000   37.5000   35.0000   32.5000   30.0000   27.5000   25.0000   22.5000   20.0000   17.5000

  Columns 11 through 18

   15.0000   12.5000   10.0000    7.5000    5.0000    2.5000         0   -2.5000

x3 =

     2     4     6     8    10    12    14    16    18    20  

 

2. Imagine you are running an experiment where stimuli flash onto the screen. Subjects are asked to hit the 'r' key if they see a face that looks like Russell Crowe and 'e' if they see a face that looks like Eddie Izzard. While you are piloting the experiment you make the faces alternate on every trial, so you expect the results of 40 trials to look as follows:

resp='rererererererererererererererererererere';  

a) Now imagine that while you were piloting you were distracted on what you thought was the 5th trial and hit the 'k' key. So resp now looks like this:

 resp='rerekererererererererererererererererere';  

 

How would you check that it was the 5th trial that contained the 'k'?

b) Replace the 'k' with a 'r'

c) How would you check to see that you always pressed a 'e' for Eddie Izzard (Hint, use x3 from Exercise 1).