MATLAB Part 2 - Matlab Arrays

Dave White

Arrays

Vector

1xN or Nx1 Array
Mathematically - a collection of variables describing a feature/object

% Row Vector
V=[1 2 3 4]
size(V)

% Column
V=[1; 2; 3; 4]
size(V)

% ROW
V=1:4

% Column
V=1:4'  %' is transpose


%Also technically a vector
V=1
size(V)

Vectors from ranges

1:9                               % Range
1:2:9                             % Increment by 2
1:2:8                             % Non inclusive
L=linspace(1,9,10)                % 10 values equally spaced between 1 and
load('myfunctions')
x=linspace(-5,5,1000)
y=f(x)
plot(x,y);
xlabel('x values')
ylabel('y values')
title('function f')

Grids
Say we want a 2D version of linspace for 3D functions
We need to evaluate at both x and y

L=linspace(1,9,10)         % 10 values equally spaced between 1 and 9
plot(L,L,'.')              % This won't work
[X,Y]=meshgrid(L);         % This distributes x and y
plot(X,Y,'.k')             % This works.

We will return to this after we look at some 2D plots, but first strings ->

Matrix

NxM
Mathematically - a linear "operator" composed of rotations and scaling
Practically - can be thought of as a collection of vectors


V=[1 4 7 10; 2 5 8 11; 3 6 9 12];

V=[1 4 7 10; ...
   2 5 8 11; ...
   3 6 9 12]

V=1:12'
V=resize(V,3,4)
size(V)

V=rand(3,4)

Tensor

NxMxO Array and Arrays beyond 3 dimensions

V=rand(3,4,5,4)

V=rand(3,4)
V=resize(V,1,3,4)

Strings

Array of char

d='t'                        % Character to variable
c='This is a string'         % String to variable
% what if I didn't use quotes? what would that mean?

c=['T' 'h' 'i' 's']
c=['This' 'is' 'my string']
c=['This is my string']
c=['t'; 'h'; 'i'] % don't work well as column vectors
c=['t'; 'h'; 'i']'

Memory management

A=rand(1000);

Where is the symbol A located in memory?
What is A bound too?
Where is the matrix data located?

B=A;

What is happening?

B=B+1;

Copy on eval
B is an alias for A until we modify A or B

Python

import numpy

A=numpy.random.rand(100)
B=A
A=A*3

A
B

R and Numpy mimics matlab matrix memory management

Array Basics

Manual array construction

A=[1 2 3]
A=[7/2 11/3 3/2]                  % A row vector (1x3 matrix)
B=[7/2, 11/3, 3/2]                % Also a row vector
C=[7/2; 11/3; 3/2]                % Column vector (3x1 matrix)
A=[7/2 11/3 3/2; 3 2 1; 3, 2, 1]  % A 3x3 matrix

New column with comma and/or space
Either a comma or space is required, or can have both

Functions and operators are designed to work on matrices

A=[7/2 11/3 3/2]
B=[3 2 1]
A+B
A-B

Matrix operations vs element wise operations

A*B                               % Invalid
A'                                % Transpose
A'*B                              % Inner product, a type of dot product - measures similarity between vectors
A*B'                              % Outer product
A.*B                              % Element wise product
A'/B                              % A matrix multiplied by inverse B
A./B                              % Element wise division
A'^B                              % Repeated auto-inner product
A.^B                              % Element wise exponent

Functions on arrays

round(A)
size(A)
size(8)                           % 8 is a 1x1 array!

Combining arrays

A=[1 2 3];
B=[4 5 6];
[A B]
C=[7; 8; 9];
[A C]                             % This doesn't work
[A C']                            % This does

DO EXCERCISE 2

What about functions?

f=@(x) x.^2+3                % With 1 input
size(A) % also an array

Array comparison

Comparing Arrays

A==B

isequal(A,B)

s1='perl'
s2='python'

isequal(s1,s2)
strcmp(s1,s2)

DO EXERCISE 3

Indexing

Two ways of references elements in a matrix
Indexing - Single value
Subscripts - Two values

Indexing runs down columns then rows:

1 4 7
2 5 8
3 6 9

Subscripts - specifies rows then columns

1,1 2,1 3,1
1,2 2,2 3,2
1,3 2,3 3,3

Either way RC (rows then columns)

A=[80 106 32; 90 70 4; 3 1 2]
A(1)            % First elements
A(1:3)          % Elements 1 through 3
A(:)            % All elements
A(1:end)        % Elements 1 through the last
A(2:end-1)      % Second element to the second to last element
B=A(:)          % Matrix to column vector
A <- c(1,2,3)
A[1]
A[1:3]
A[1:length(A)-1]

R same, but with square braces and without "end" feature


import numpy
A=numpy.array([1, 2, 3])
A[1]
A[0]
A[1:]
A[0:3];
A[:-1]
A[:0]

python is pretty strange, more on that later

Subscripts

A=[80 106 32; 90 70 4; 3 1 2]
A(1,3)                        % Element in first row, third column
A(1:3,1:2)                    % Elements in 1-3 rows with 1-2 columns
A(1,:)                        % Everything in the first row
A(2:end-1,:)                  % Everything but the first row

Trick to remember:
Index - Individual
Subscripts - Begins with s - plural

[n,m]=find(A==3)
ind=sub2ind(sz,sub1,sub2)
ind=ind2sub(sz,ind)

subscripting work the same in R and python, but

Array Summary

Length

A=rand(10,1)
B=rand(1,10)
A=length(A);               % Size of largest dimension
B=length(B);               % Size of largest dimension

Size

size(A)                    % Size of all dimensions
size(A,1)                  % Query dimensions
size(A,2)
numel(A)                   % Number of elements in matrix

sum(A,1)                   % Add all elements accross rows
sum(A,2)                   % Add all elements accross columns
sum(A)                     % Default to sum accross rows (dimension 1), leaving row vector
min(A,[],1)                % Minimum values in rows
max(A,[],2)                % Maximum values in rows
min(A,B,1)                 % Minimum values in rows between A & B
min(A,B,2)                 % Minimum values in columns between A & B

imagesc(A)
colorbar

DO EXCERCISE 8

Editing matrices

Editing Matrices

A=zeros(10)
A(1)=1
A(2:end-1)=0
A(:,1)=rand(10,1);

Deleting values
size(A)

A(1,:)=[]
size(A)
A(1)=[]
size(A)

Combining matrices

B=ones(10)
[A B]
a=1
b=[2 1]
[a b [1 3 4]]
[a b'] invalid

DO EXCERCISE 7

Random Numbers

Matrix query/Creation functions
These take the following form:

<function>(nRows,nColumns)
    OR
<function>(nRows/Columns) %if square matrix

Random matrices

rand(3,1)          % 3x1 matrix with elements sampled uniform distribution between zero and 1
rand(1,3)          % 1x3 matrix
rand(3,3)          % 3x3 matrix
rand(3)            % 3x3 matrix

Controlling the randomness

rng(3)             % rng sets the random seed
rand(5)            % Note the value here
rand(5)
rng(3)
rand(5)            % The value here should be the same as above

Expanding Rand

Many times you need some regular matrix, but no function exists
No function to sample between -30 & 30 exists
How to get values between -30 & 30?
rand(3,3)*60-30

Tensors
What happens if we do more than 2 dimensions)?
rand(3,3,3) 3D matrix aka tensor
Can't show a 3d matrix at once, so it shows slices
Showing subscripts of each dimension
':' means all elements

Large Outputs and semicolon

rand(100,100,100)           % Should produce a large output
<C-c>                       % Cancels operation
rand(100,100,100);          % Semi-colon supresses output
rand(1000,1000,1000);       % You should get an error about memory limitations
A=rand(100); B=rand(200);   % Semicolon can separate commands on same line

Randi

randi(100,3,2)              % 3x2 matrix with random integers between 1 & 100

Other important

ones()                      % Matrix of just ones
zeros()                     % Matrix of zeros
eye()                       % Identity matrix

Plotting Preview - Binning

Histogram

figure(1)
A=randn(1000,1)          % Normally distributed random numbers
histogram(A)             % Histogram, automatically setting the number of bins
histogram(A,10)          % Set number of bins to 10
help histogram

Figure 5 - bar

figure(5)
counts=[countsA; countsB]
bar(ctrsA,counts')
bar(ctrsA,counts',1)
bar(ctrsA,counts','stacked')
close all                 % Close all figures

figure(5)
plot(ctrsA,countsB,'k')
hold on
plot(ctrsB,countsB,'r')
close all

DO EXCERSISE 9