You are on page 1of 7

# Entering Matrices MATLAB

Tutorial Enter an explicit list of elements Load matrices from files Generate them using built-in functions Create them with your own functions

## When entering matrices

Separate elements with blanks or commas Use semicolon ; to indicate end of row List enclosed in square brackets [ ]

Example
>> A = [21, 22, 23;39,40,41;71,72,73] A= 21 39 71 22 40 72 23 41 73

## Some Useful Matrix Functions

sum(A) sums up the columns A transpose diag(A) main diagonal sum(A) sum of rows sum(diag(A)) sum of main diagonal sum(diag(fliplr(A))) sum of antidiagonal If no output variable is specified, MATLAB uses ans

Example
>> sum(A) ans = 131 134 137

## Accessing a specific element

A(row, column) to access a specific element of matrix A A(k) is the usual way of referencing row and column vectors A(k) can also be used to reference a single element of a 2D Matrix
>> A(2,1) ans = 39 >> A(2)

Examples

ans = 39

## Outside the Matrix

Error if you try to read from a value of an element outside the matrix If you write to it on the other hand, the matrix will expand to accommodate it

Example
>> A(2,4) = 42 A= 21 39 71 22 40 72 23 41 73 0 42 0

Sequences
1:7 is a row vector 1 2 3 4 5 6 7 Initial:increment:final >> 0:pi/4:pi ans = 0 0.7854 1.5708 2.3562 3.1416

Portions of a matrix
>> A(2,2:4) ans = 40 41 42

## All and end

: by itself means all End means last row or last column >> A(end,:) ans = 71 72 73 0

## Vectors and Scalars

A matrix with one row or one column is a vector A scalar is a one by one matrix >> num_students = 25 num_students = 25

Built-in Functions
help elfun: list of elementary functions help specfun, help elmat for more advanced matrix functions

Examples of Expression
rho = (1+sqrt(5))/2 rho = 1.6180 a = abs(3+4i) a= 5 z = sqrt(besselk(4/3,rho-i)) z= 0.3730+ 0.3214i huge = exp(log(realmax)) huge = 1.7977e+308 toobig = pi*huge toobig = Inf

Generating Matrices
zeros: all zeroes ones: all ones rand: uniformly distributed random elements randn: normally distributed random elements
>> randn(4,4) ans =

Example

-2.1707 0.5077 0.3803 0.0000 -0.0592 1.6924 -1.0091 -0.3179 -1.0106 0.5913 -0.0195 1.0950 0.6145 -0.6436 -0.0482 -1.8740

Data Files

Code Files
M-files are text files containing MATLAB code can be created using MATLAB editor or any other text editor have a .m extension

Concatenation
Joining small matrices to make bigger one >> big = [zeros(2,2) ones(2,2);ones(2,2) zeros(2,2)] big = 0 0 1 1 0 0 1 1 1 1 0 0 1 1 0 0

Deleting
You can delete rows and columns using the square brackets [ ] X(:,2) = [] deletes the second column of the matrix You can delete a single element from a matrix; however, you would end up reshaping the remaining elements into a row vector

Operators
A + A adding a matrix to a transpose produces a symmetric matrix * denotes matrix multiplication involving inner products between rows and columns A * A multiplying a transpose by the original produces a symmetric matrix use .* for element-by-element multiplication ./ element-by-element division .^ element-by-element power

Building Tables
>> n = (0:4)'; >> rows = [n n.^2 2.^n] rows = 0 1 2 3 4 0 1 4 9 16 1 2 4 8 16

Logical Subscripting
X= 6 14 32 50 NaN

Another Example
Highlight primes by setting non-primes to zero: >> A(~isprime(A)) = 0 A= 0 0 71 0 23 0 41 0 73

>> X = X(finite(X)) X= 6 14 32 50

find
find picks out the locations, using onedimensional indexing >> k = find(isprime(A))' k= 3 7 8 9

Display
help format: to display different ways of formatting displayed numbers use semicolons ; to suppress output use to continue a statement on another line

if
if <condition> <action> elseif <condition> <action> else <action> end

example
if rem(n,2) ~= 0 M = odd_magic(n) elseif rem(n,4) ~= 0 M = single_even_magic(n) else M = double_even_magic(n) end

## Some functions helpful for if

isequal checks if two matrices are equal == will not do that, it will check where they are equal instead isempty all any

## switch and case

switch (rem(n,4)==0) + (rem(n,2)==0) case 0 M = odd_magic(n) case 1 M = single_even_magic(n) case 2 M = double_even_magic(n) otherwise error('This is impossible') end

for
for n = 3:32 r(n) = rank(magic(n)); end r while <condition> . . . end

while

example
while T < Number_of_iterations % pheromone values ^ Alpha Weighted_pheromones = Pheromone .^ Alpha; % initialise the ants' memory to zeros Ants_memory = zeros(Number_of_departments, Number_of_departments); % move the ants one interation (please examine function move_ants) [Ants_memory, Best_Cost, Optimal_Assignment] = ... move_ants(Number_of_departments, Number_of_ants, ... Weighted_pheromones, Weighted_distance_costs, ... Given_flow, Given_distance, Ants_memory, Best_Cost, ... Q, Optimal_Assignment); % update the pheromone values using the ants' memory Pheromone = update_pheromone_levels(Lambda, Pheromone, Ants_memory); T = T + 1; end

functions
functions are M-files can accept input arguments return output arguments first line starts with keyword function it gives function name & order of arguments

example
% function accepts: % number of departments % list of probabilities % returns a chosen site based on the corresponding probabilities % represented in the probabilities vector function Chosen_site = choose(Number_of_departments, Probabilities) % random number between 0 and 1 Random_number = rand; % calculate cumulative probabilities for i = 1:Number_of_departments - 1 Probabilities(i + 1) = Probabilities(i + 1) + Probabilities(i); end % take whatever is before where the random number falls Chosen_site = Number_of_departments + 1 - sum(Random_number < Probabilities);

global variables
if you want more than one function to share a variable global declaration must occur before the variable is actually used in the function capital letters is not a must, just a convention

example
function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2;