Chapter 3. Matrices, Calculations and Logical operations

 

Matrices

As mentioned in the earlier chapter, you can have lists of numbers as well as of letters. These list of numbers can be either one-dimensional, in which case they called a vector. When they are two, three, or more-dimensional they are called a matrix.

 

mat1=[1 54 3; 2 1 5; 7 9 0; 0 1 0]  

 

mat1 =

     1    54     3

     2     1     5

     7     9     0

     0     1     0  

 

mat2=[1 54 3

  2 1 5

  7 9 0

  0 1 0]  

 

mat2 =

     1    54     3

     2     1     5

     7     9     0

     0     1     0  

 

Take a look at mat1 and mat2. As you can see there is more than one way of entering a matrix. mat1 and mat2 were entered differently, but both have 4 rows and 3 columns. When entering matrices a semi-colon is the equivalent of a new line.

 

You can find the size of matrices using the command size.

 

size(mat1)  

 

ans =

     4     3  

 

For a two dimensional matrix the first value in size is the number of rows. The second value of size is the number of columns.

 

Now try:

 

vect1=[1 2 4 6 3]

vect2=vect1'  

 

vect1 =

     1     2     4     6     3

vect2 =

     1

     2

     4

     6

     3  

 

Vectors can be tall instead of long. The single quote '  is a transpose, and allows you to switch  rows and columns of a matrix or vector.

 

Remember the command whos which will tell you the size of all your variables at once? Use whos to look at the size of mat1, mat2, vect1 and vect2.

 

whos  

 

  Name       Size            Bytes  Class     Attributes

 

  ans        1x2                16  double             

  mat1       4x3                96  double             

  mat2       4x3                96  double             

  vect1      1x5                40  double             

  vect2      5x1                40  double             

  x          5x1                40  double             

  y          1x2                16  double                

 

Addition and subtraction

You can perform various calculations on matrices and arrays. You can add a single number (generally called a scalar) to a vector.

 

vect1+3  

 

ans =

     4     5     7     9     6  

 

You can subtract a scalar.

 

vect2-3  

 

ans =

    -2

    -1

     1

     3

     0  

 

You can add a vector onto itself

 

vect1+vect1  

 

ans =

     2     4     8    12     6  

 

You can also add two vectors as long as they are the same size. You can’t add vect1 and vect2 together since they are different sizes.

 

vect1+vect2  

 

??? Error using ==> plus

Matrix dimensions must agree.  

 

Scalar?

In physics a scalar is a value that only has magnitude (and not direction). In programming a scalar is defined as a quantity that can only hold a single value at a time, i.e. a single number or character. Generally the expression scalar tends to be used to refer to numbers rather than characters. 

 

BUG BOX – Matrix dimensions must agree

 

vect3= [1 2 3 4]

vect4=[ 1 3 5 2]';

vect3+vect4;  

 

vect3 =

     1     2     3     4

??? Error using ==> plus

Matrix dimensions must agree.  

 

You get this error if you try to add vectors of inappropriate sizes. To successfully add two vectors they must be the same orientation as well as the same length – i.e. you can't add a tall thin vector to a short fat vector. The same goes for other operations (subtraction, point-wise multiplication & division and matrix multiplication & division) and applies to matrices as well as vectors.

 

mat1=[1 2 3; 4 5 6];

mat2=[1 2; 3 4; 5 6];

mat1-mat2'  

 

ans =

     0    -1    -2

     2     1     0  

 

mat1-mat2  

 

??? Error using ==> minus

Matrix dimensions must agree.  

 

So when you get this error the first thing you should do is check the size of all the variables that you are tying to manipulate, and try to work out why Matlab thinks they are mismatched in size or shape. Often it’s the case that simply transposing one of the variables is all you need to do. This is an important thing to understand, so make sure you understand this box.

 

Scalar multiplication and division 

Here you simply use the symbols * and /. You can a multiply a scalar with another scalar, with a vector, or with a matrix.

 

2*3  

 

ans =

     6  

 

2/3  

 

ans =

    0.6667  

 

vect1*3 

 

ans =

     3     6    12    18     9  

 

vect1/2 

 

ans =

    0.5000    1.0000    2.0000    3.0000    1.5000  

 

mat1*0.5 

 

ans =

    0.5000    1.0000    1.5000

    2.0000    2.5000    3.0000  

 

Vector multiplication and division

Point-wise multiplication and division

As you may or may not remember from high school math there are actually three sorts of multiplication and three sorts of division when you are multiplying vectors (or matrices) with each other. They are called point-wise, inner-product, and outer-product multiplication.  We'll now describe each of them.

 

Point-wise (or element by element) multiplication and division is the first, and simplest. In Matlab these are computed to using .* and ./ (notice the period character). 

 

vect1=[1 2 3 4];

vect2=[2 3 4 5];

 

vect1.*vect2  

 

ans =

     2     6    12    20  

 

vect2.*vect1  

 

ans =

     2     6    12    20  

 

vect1./vect2  

 

ans =

    0.5000    0.6667    0.7500    0.8000  

 

vect2./vect1  

 

ans =

    2.0000    1.5000    1.3333    1.2500  

 

 

Figure 3.1 Point-wise multiplication of two vectors.

 

Each element in the first vector is multiplied by the corresponding element in the second vector. Like with addition and subtraction the vectors must be the same shape.

 

Note what happens if we make one of the two vectors tall and thin (note the ' transpose in the examples below).

 

vect1.*vect2'  

 

??? Error using ==> times

Matrix dimensions must agree.  

 

vect1./vect2'  

 

??? Error using ==> rdivide

Matrix dimensions must agree.  

 

Here's another example.

 

mat1=[1 2 3; 4 5 6]

vect1.*mat1  

 

mat1 =

     1     2     3

     4     5     6

??? Error using ==> times

Matrix dimensions must agree.  

 

This multiplication is not going to happen for you, regardless of how you transpose mat1 and vect1. These two variables will never be the same size, no matter what you do.

 


 

Inner product (dot product)

The second kind of multiplication, the inner-product or dot product is a bit more complicated but is actually considered the standard or default way. Here, when multiplying vectors  A and B the number of columns in A need to match the number of rows in B.

 

clear all

x=[1 2 4];

y=[1.1 2.2 3.3];

whos  

 

  Name      Size            Bytes  Class     Attributes

 

  x         1x3                24  double             

  y         1x3                24  double                

 

Both x and y have one row and three columns.

 

The inner product is calculated when A has a single column, and B has a single row.

 

z1=x*y'  

 

z1 =

   18.7000  

 

z2=y*x'  

 

z2 =

   18.7000  

 

Note that you get the same answer both times.

 

 

Figure 3.2 The inner product of two vectors.

 

Outer product

 

The outer product is calculated when A has multiple columns and B has multiple rows. Note that the number of columns in A needs to match the number of rows in B. The outer product makes a matrix for which each element is the product of the value from the corresponding row in A and from the column in B.  Both the inner and outer products are computed using the '*' symbol.  Matlab knows which to use by the the size of the vectors.

 

z3=x'*y 

 

z3 =

    1.1000    2.2000    3.3000

    2.2000    4.4000    6.6000

    4.4000    8.8000   13.2000  

 

z2=y'*x 

 

z2 =

    1.1000    2.2000    4.4000

    2.2000    4.4000    8.8000

    3.3000    6.6000   13.2000  

 

Figure 3.3 The outer product of two vectors.

 

The following multiplications aren't allowed because the number of columns in A doesn't match the number of rows in B.

 

x*y  

 

??? Error using ==> mtimes

Inner matrix dimensions must agree.  

 

y*x  

 

??? Error using ==> mtimes

Inner matrix dimensions must agree.  

 

x'*y'  

 

??? Error using ==> mtimes

Inner matrix dimensions must agree.  

 

y'*x'  

 

??? Error using ==> mtimes

Inner matrix dimensions must agree.  

 

Matrix multiplication and division

 

Similarly to vectors, the matrix product C = A*B is only defined when the column dimension of A is equal to the row dimension of B.

 

The size of the output depends on how you multiply the output. If A is m-by-p and B is p-by-n, their product C is m-by-n. I.e. C has the same number of rows as A and the same number of columns as B.

 

clear all

A=[1 2; 3 4; 5 6]; 

B=[1.1 2.2 3.3 4.4; 5.5 6.6 7.7 8.8];

whos  

 

  Name      Size            Bytes  Class     Attributes

 

  A         3x2                48  double             

  B         2x4                64  double                

 

 

C=A*B  

 

C =

   12.1000   15.4000   18.7000   22.0000

   25.3000   33.0000   40.7000   48.4000

   38.5000   50.6000   62.7000   74.8000  

 

 


Since A has 3 rows and B has 4 columns C has 3 rows and 4 columns.

 

D=B'*A'  

 

D =

   12.1000   25.3000   38.5000

   15.4000   33.0000   50.6000

   18.7000   40.7000   62.7000

   22.0000   48.4000   74.8000  

 

Figure 3.4 Two examples of matrix multiplication.

 

Here are a few examples of operations that aren't allowed because the number of columns in A doesn't match the number of rows in B

 

B*A  

 

??? Error using ==> mtimes

Inner matrix dimensions must agree.  

 

A*B'  

 

??? Error using ==> mtimes

Inner matrix dimensions must agree.  

 

Here's another example. In this case A and B are the same size and shape, with two rows and three columns.

 

A=[1 2 3; 4 5 6];

B=[7 8 9; 10 11 12];

whos  

 

  Name      Size            Bytes  Class     Attributes

 

  A         2x3                48  double             

  B         2x3                48  double             

  C         3x4                96  double             

  D         4x3                96  double                

 

Let's begin by orienting the matrices such that A has two rows and B has two columns. The output matrix should be two by two.

 

C=A*B'  

 

C =

    50    68

   122   167  

 

We can get a similar result (transposed) if we reverse the order of multiplication and transpose both matrices (B' transposed, is of course simply B).

 

C=B*A'  

 

C =

    50   122

    68   167  

 

Then look what happens if we orient the matrices in such a way that A has three rows and B has three columns. The output matrix is completely different – this time a three by three matrix.

 

C=A'*B  

 

C =

    47    52    57

    64    71    78

    81    90    99  

 

C=B'*A  

 

C =

    47    64    81

    52    71    90

    57    78    99  

 

More Calculation Stuff

 

To raise 10 to the 5th power (105) you simply do the following:

y=10^5

 

To do this with vectors you need to add the period. You need to use the period regardless of whether you are taking a vector and raising it to to a single number, taking a single number and raising it to a vector, or taking a vector and raising it to another vector (which will need to be of the same size and shape).

 

y=[1:5].^2  

 

y =

     1     4     9    16    25  

 

y=2.^[1:5]  

 

y =

     2     4     8    16    32  

 

y=[1:5].^[1:5]  

 

y =

           1           4          27         256        3125  

 

You can take either the natural or the base 10 log of a number. The default is the natural log.

 

y=log(10)  

 

y =

    2.3026  

 

y=log10([3 10])  

 

y =

    0.4771    1.0000  

 

The exponential function ex is simply:

 

y=exp(1:3)  

 

y =

    2.7183    7.3891   20.0855  

 

Other useful commands are round, min and max.

 

round(3.14)  

 

ans =

     3  

 

round(pi)  

 

ans =

     3  

 

x=1:5;

min(x)  

 

ans =

     1  

 

x=[1 2 3 4 5; 1.1 2.2 3.3 4.4 5.5]

min(x)  

 

x =

    1.0000    2.0000    3.0000    4.0000    5.0000

    1.1000    2.2000    3.3000    4.4000    5.5000

ans =

     1     2     3     4     5  

 

Note that min takes the minimum of each column, not the minimum of the entire matrix. The command max works in a similar way.

max(x')  

 

ans =

    5.0000    5.5000  

 

Multidimensional matrices

Matrices can be 3, 4 or more dimensions, though some commands won’t work for matrices with more than 2 or 3 dimensions

 

clear mat

mat(1, :,:) =[0 1 1 0 ; 0 0 0 0 ; 0 0 0 1 ; 0 1 0 0 ; 0 0 1 0 ];

mat(2, :, :)=[1 0 1 1 ; 1 0 1 1 ; 0 0 0 0 ; 0 0 0 0 ; 0 1 0 0 ];

mat(3, :, :)=[0 0 0 0 ; 1 1 0 1 ; 0 0 0 0 ; 0 0 0 0 ; 0 0 0 0 ];

 

size(mat)  

 

ans =

     3     5     4  

 

 

mat  

 

mat(:,:,1) =

     0     0     0     0     0

     1     1     0     0     0

     0     1     0     0     0

mat(:,:,2) =

     1     0     0     1     0

     0     0     0     0     1

     0     1     0     0     0

mat(:,:,3) =

     1     0     0     0     1

     1     1     0     0     0

     0     0     0     0     0

mat(:,:,4) =

     0     0     1     0     0

     1     1     0     0     0

     0     1     0     0     0  

 

 

Figure 3.5 A three dimensional matrix.

 

There are many circumstances where a three-dimensional matrix is useful in the behavioral sciences. One of the most common examples is when you want to present subjects with a series of images over time. In that case it is very natural to use the first and second dimensions to represent each image, and the third dimension to represent time.

In that case, if you wanted to look at the first image presented in time you would reference it as follows:

 

mat(:, :, 1)  

 

ans =

     0     0     0     0     0

     1     1     0     0     0

     0     1     0     0     0  

 

The third image in time would be:

 

mat(:, :, 3)  

 

ans =

     1     0     0     0     1

     1     1     0     0     0

     0     0     0     0     0  

 

If instead, you wanted to look at what was happening in the top left corner of the screen over time, you would reference it as follows:

 

mat(1, 1, : )  

 

ans(:,:,1) =

     0

ans(:,:,2) =

     1

ans(:,:,3) =

     1

ans(:,:,4) =

     0  

 

If you wanted to know what was happening in the bottom line of the screen in the first image you would reference it as:

 

mat(3, :,1)  

 

ans =

     0     1     0     0     0  

 

Finally, if you wanted to know what was happening in the bottom line of the screen over time:

 

mat(3, :, : )  

 

ans(:,:,1) =

     0     1     0     0     0

ans(:,:,2) =

     0     1     0     0     0

ans(:,:,3) =

     0     0     0     0     0

ans(:,:,4) =

     0     1     0     0     0  

 

Functional magnetic resonance data is generally represented in four dimensional matrices. The first two dimensions each represent a single image (slice) through the brain. The third dimension represents all the slices needed to represent the entire brain. The fourth dimension represents the time course of the experiment. You can think of it as multiple cubes over time (or not).

 

Making matrices.m

 

 % MakingMatrices.m

 % This program provides examples of cunning ways

 % that you can create matrices.

 % written by IF 3/2007 

 

mat1=zeros(10, 8); 

 

The command zeros(10, 8) creates a matrix containing all zeros with ten rows and eight columns.  Also try using the command ones (which works in a similar way) to make a matrix with 7 rows and 3 columns. Remember that the first dimension in a matrix is the rows, and the second dimension is the columns.  

 

In this next example you are setting all the rows in the third column to be 1.

 

mat2=mat1;

 

mat2(1:10, 3)=1  


 

 

Another way of writing this command would be as follows, here instead of having to know that mat2 has ten rows, we use the expression 1:end to tell Matlab to use the vector that goes from the first row to the last row.

 

mat2=mat1;  

mat2(1:end, 3)=1  

 

Finally, here's an even more succinct shortcut where we simply use a colon to tell Matlab to include all rows.

 

mat2=mat1;  

mat2(:, 3)=1  

 

mat2 =

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     1     0     0     0     0     0  

 

 

Now let's set all the columns in the fourth row to be 1. The colon now means to include the entire column.

 

mat3=mat1;

mat3(4, 1:8)=1;   

 

Other ways of writing this command would be:

or

mat3(4, 1:end)=1;   

or

 mat3(4, :)=1;  

 

Here we create a matrix that is four by four zeros (it is a weirdness of the zeros command that the convention is simply giving a single argument (4) makes a 4x4 square matrix).

 

Then we go through each row of the matrix, and replace the place in the matrix that is the i-th row and i-th column with the number i. We are doing this using a for loop. Matlab will go through the loop four times. Each time it goes through the loop it will wait at the pause command for you to press a key. 

 The first time it goes through the loop i will be equal to 1, so the command  mat4(i, i)=i; will be the equivalent of mat4(1, 1)=1. The second time it goes through the loop i will be 2, so mat4(2, 2)=2, and so on up to i=4, mat(4, 4)=4. I've left the semicolon off so you can watch mat4 gradually change.

 

mat4=zeros(4);

for i=1:4

    mat4(i, i)=i

    pause

end 

 

mat4 =

     1     0     0     0

     0     0     0     0

     0     0     0     0

     0     0     0     0

mat4 =

     1     0     0     0

     0     2     0     0

     0     0     0     0

     0     0     0     0

mat4 =

     1     0     0     0

     0     2     0     0

     0     0     3     0

     0     0     0     0

mat4 =

     1     0     0     0

     0     2     0     0

     0     0     3     0

     0     0     0     4  

 

 

In this example we sequentually go through five rows of a matrix filling the columns with a vector that depends on which row it is.

 

mat5=zeros(6);

for i=1:6

    mat5(i,:)=[-2 0 -1 1 2 3]

   pause

end  

 

mat5 =

    -2     0    -1     1     2     3

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

mat5 =

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

mat5 =

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

mat5 =

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

     0     0     0     0     0     0

     0     0     0     0     0     0

mat5 =

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

     0     0     0     0     0     0

mat5 =

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3

    -2     0    -1     1     2     3  

 

As we went through the loop six times, we filled the columns one through six of mat5 with the vector -2:3.

 

Next,  try doing the samet thing but using the vector [-1 -2 0 -1 1 2 3].

 

mat5=zeros(6);

for i=1:6

    mat5(i,:)=[-1 -2 0 -1 1 2 3]

   pause

end 

 

??? Subscripted assignment dimension mismatch.  

 

You get an error! This is because you are trying to squeeze a vector that is 1 row and seven columns ([-1 -2 0 -1 1 2 3]) into the row of a matrix that only has six columns.

BUG BOX – Subscripted assignment dimension mismatch

x=zeros(4);

x(2, :)=1:5;  

 

??? Subscripted assignment dimension mismatch.  

 

This gives an error because you are trying to squeeze a vector that is 1 row and 5 columns into the row of a matrix that only has four columns. You often get this error because one of your vectors or matrices is the wrong shape, as in the example here.

x=zeros(2, 4);

y=ones(5, 5);

x(:, :)=y;  

 

??? Subscripted assignment dimension mismatch.  

 

Weirdly, the following command, which seems identical, will work.

 

x=zeros(2, 4);

y=ones(5, 5);

x(1:5, 1:5)=y

 

Wha? When you refer to rows and columns on the left hand side of the equals sign this tells Matlab you want the variable x to be expanded to include that many rows and columns. This expansion means there's now enough space for y.  This is very weird and at this point you shouldn't worry about it much. Just remember that the subscripted assignment dimension error means you are trying to fit a square peg into a round hole.

 

Here's yet another matrix. Here we are saying we want to place ones in the matrix where the rows are between two through five and the columns are between one and three.

 

mat6=zeros(6);

mat6(2:5, 1:3)=1  

 

mat6 =

     0     0     0     0     0     0

     1     1     1     0     0     0

     1     1     1     0     0     0

     1     1     1     0     0     0

     1     1     1     0     0     0

     0     0     0     0     0     0  

 

In the next example, what we put into the matrix on each iteration of the loop depends on the value of i. When i is one, then the vector [1 1 2 2 1] is put into the first row of mat7. When i is two, then the vector [2 2 3 3 2] is put into the second row of mat7 and so on.

 

mat7=zeros(5);

for i=1:5

    mat7(i, :)= [0 0 1 1 0]+i;

end

mat7  

 

mat7 =

     1     1     2     2     1

     2     2     3     3     2

     3     3     4     4     3

     4     4     5     5     4

     5     5     6     6     5  

 

 

Now let's do the same thing but we'll put the vectors in along the columns instead of the rows. All we need to do is change mat7(i, : ) to mat7(:, i).

 

mat7=zeros(5);

for i=1:5

    mat7(:, i)= [0 0 1 1 0]+i;

end

mat7  

 

mat7 =

     1     2     3     4     5

     1     2     3     4     5

     2     3     4     5     6

     2     3     4     5     6

     1     2     3     4     5  

 



 

 

 

Technically we're trying to vector that has one row and five columns into a space that has five rows and one columns. So if Matlab wanted to be pedantic it would give the Subscripted assignment dimension mismatch error. But Matlab, rather tolerantly, will let this one go. It would be better style to make the two vectors match in shape by transposing the right hand side as follows:

 

    mat7(:, i)=[0 0 1 1 0]'+i

 

 

In the next example we are using a nested loop. Basically it is one for loop inside another. So in this example we use i go down each row. For each value of i we then use j to go through each column in turn. 

 

mat8=zeros(3, 4);

for i=1:3

    for j=1:4

        mat8(i, j)=i+j

    end

end  

 

mat8 =

     2     0     0     0

     0     0     0     0

     0     0     0     0

mat8 =

     2     3     0     0

     0     0     0     0

     0     0     0     0

mat8 =

     2     3     4     0

     0     0     0     0

     0     0     0     0

mat8 =

     2     3     4     5

     0     0     0     0

     0     0     0     0

mat8 =

     2     3     4     5

     3     0     0     0

     0     0     0     0

mat8 =

     2     3     4     5

     3     4     0     0

     0     0     0     0

mat8 =

     2     3     4     5

     3     4     5     0

     0     0     0     0

mat8 =

     2     3     4     5

     3     4     5     6

     0     0     0     0

mat8 =

     2     3     4     5

     3     4     5     6

     4     0     0     0

mat8 =

     2     3     4     5

     3     4     5     6

     4     5     0     0

mat8 =

     2     3     4     5

     3     4     5     6

     4     5     6     0

mat8 =

     2     3     4     5

     3     4     5     6

     4     5     6     7  

 

Here's a tricky one for you:

 

mat9=zeros(3,4);

for i=1:3

    for j=1:4

        mat9(i, j)=((i-1)*4)+j

    end

end  

 

mat9 =

     1     0     0     0

     0     0     0     0

     0     0     0     0

mat9 =

     1     2     0     0

     0     0     0     0

     0     0     0     0

mat9 =

     1     2     3     0

     0     0     0     0

     0     0     0     0

mat9 =

     1     2     3     4

     0     0     0     0

     0     0     0     0

mat9 =

     1     2     3     4

     5     0     0     0

     0     0     0     0

mat9 =

     1     2     3     4

     5     6     0     0

     0     0     0     0

mat9 =

     1     2     3     4

     5     6     7     0

     0     0     0     0

mat9 =

     1     2     3     4

     5     6     7     8

     0     0     0     0

mat9 =

     1     2     3     4

     5     6     7     8

     9     0     0     0

mat9 =

     1     2     3     4

     5     6     7     8

     9    10     0     0

mat9 =

     1     2     3     4

     5     6     7     8

     9    10    11     0

mat9 =

     1     2     3     4

     5     6     7     8

     9    10    11    12  

 

 

That was another nested loop. This trickiness of using ((i-1)*4)+j means that when we are on the first row, the columns are labeled as 1,2,3,4. When we are on the second row the columns are labeled as 5,6,7,8 and so on …

 

How did we do this? When i=1 then ((i-1)*4)=0, so the columns are filled with the value of j. When i=2 then ((i-1)*4)=4, so the columns are filled with the value of j+4, and so on.

 

In fact, you don't do a nested loop to do this – here's how to do this with a single loop.

 

mat9=zeros(3,4);

for i=1:3

 mat9(i, :)= ((i-1)*4)+[1:4]

end  

 

mat9 =

     1     2     3     4

     0     0     0     0

     0     0     0     0

mat9 =

     1     2     3     4

     5     6     7     8

     0     0     0     0

mat9 =

     1     2     3     4

     5     6     7     8

     9    10    11    12  

 

Being able to do these sorts of manipulations is one of the keys to being able to write good code in Matlab, so take your time and make sure you understand how these examples work.

 

sub2ind and ind2sub

 

Sometimes it’s useful to convert back and forth between vectors and matrices.

 

mat=[1 2 3; 4 5 6; 7 8 9]

vect=mat(:) 

 

mat =

     1     2     3

     4     5     6

     7     8     9

vect =

     1

     4

     7

     2

     5

     8

     3

     6

     9  

 

The colon (the colon has many purposes in Matlab) tells Matlab to unwrap the matrix mat out to be a vector. Note that the unwrapped vector first lists all the rows in the first column, then lists all the rows in the second column, and so on …

 

Suppose you wanted to know where the number eight would be in the vector? Well, the number eight appears in the third row and the second column of of the matrix. The 3rd row and 2nd column are known as the row and column subscripts of the matrix mat.

 

The sub2ind command below calculates the index in vect corresponding to the 3rd row and 2nd column (the subscripts) of mat. You simply need to tell it the size of mat, and the row and columns subscripts. So:

 

ind=sub2ind(size(mat), 3, 2);

ind  

 

ind =

     6  

 

So the 3rd row and 2nd column in the matrix corresponds to the 6th index into the vector. So both of the following should give you the number eight.

 

vect(ind)  

 

ans =

     8  

 

 

mat(3,2)  

 

ans =

     8  

 

 

You can also go the other way using ind2sub. Once again you need to provide the size of the matrix and the position in the vector that you want to find the matrix subscripts for.

 

[sub_row, sub_col]=ind2sub(size(mat), 6)  

 

sub_row =

     3

sub_col =

     2  

 

Logical operations

 

These are ways of checking the truth of statements. In programming truth is expressed as being 1 and falsity is 0.

 

Is equal to

 

n1=3.2

n2=3.1

n1==n2  

 

n1 =

    3.2000

n2 =

    3.1000

ans =

     0  

 

Note that you use a single = to assign a value to a variable. You use a double equal ==  to determine whether the number of the left hand side is equal to the right hand side. The expression above gives you a 0 because the statement is false.

 

Whereas

n1=3.2;

n2=n1;

n1==n2  

 

ans =

     1  

 

Gives you a 1 because the final statement is true; n1 does equal n2

 

You can also see whether one number is not equal to another.

n1=4;

n2=4;

n1~=n2  

 

ans =

     0  

 

This is true.

 

One common way of using logical truth operations is in an if statement. An if statement checks whether the statement following the if is true or not. If the statement is true, Matlab carries out the operations between the if and the end. If the statement is false Matlab doesn't carry out those operations.

 

n=3.2

if round(n1)==n1

  disp('n is a round number');

end

  

 

n =

    3.2000

n is a round number  

 

You can also tell Matlab what to do if the statement is false, using an else.

n=3.2

if round(n1)==n1

  disp('n is a round number');

else

  disp('n is not a round number');

end

  

 

Traditionally the statement that is evaluated by an if statement is either a 1 or a 0 (true or false) but in Matlab commands followng an if statement will always be executed unless the condition following the if results in a 0.

 

n=-1;

if n

  disp('hi');

else

  disp('bye')

end  

 

hi  

 

n=0;

if n

  disp('hi')

else

  disp('bye')

end  

 

bye  

 

 

The and & and or | operators are used when you want to carry out a loop only when more than one condition is true (&) or when either of two conditions is true (|).

 

Try the following:

n1=1; n2=2; n3=3;

n1<n2 & n1>n3  

 

ans =

     0  

 

n1<n2 | n1>n3  

 

ans =

     1  

 

Exercises for Chapter 3

 

Create the following matrices (without typing in the numbers by hand):

 

Emat1 =

 

     1     6    11    16    21

     2     7    12    17    22

     3     8    13    18    23

     4     9    14    19    24

     5    10    15    20    25

 

 

Emat2 =

 

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

     1     0     1     0     1     0     1     0

 

 

Emat3 =

 

     1     0     0     0     0     0     0     0

     0     0     0     0     0     0     0     0

     0     0     1     0     0     0     0     0

     0     0     0     0     0     0     0     0

     0     0     0     0     1     0     0     0

     0     0     0     0     0     0     0     0

     0     0     0     0     0     0     1     0

     0     0     0     0     0     0     0     0

 

 

Emat4 =

 

     0     1     2     3     4

     1     2     3     4     5

     2     3     4     5     6

     3     4     5     6     7

     4     5     6     7     8

 

 

Emat5 =

 

     1     2     3     4     5

     2     4     6     8    10

     3     6     9    12    15

     4     8    12    16    20

     5    10    15    20    25

 

 

Emat6 =

 

     1     6    11    16    21

     2     7    12    17    22

     3     8    13    18    23

     4     9    14    19    24

     5    10    15    20    25

 

 

Emat7 =

 

     1     1     1     1     1     1

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

     1     1     1     1     1     1

     1     1     1     1     1     1

 

 

Emat8 =

 

     1     1     1     1     1     1

     1     0     0     0     1     1

     1     0     0     0     1     1

     1     0     0     0     1     1

     1     1     1     1     1     1

     1     1     1     1     1     1

 

 

Emat9 =

 

     1     6    11    16    21

     2     7    12    17    22

     3     8    13    18    23

     4     9    14    19    24

     5    10    15    20    25