Skip to main content
Background Image

[Linear Algebra] Matlab Basics

·1622 words·8 mins
Author
Frederic Liu
BS.c. Maths and Stats in OR
Table of Contents

Using Matlab after C feels like playing with Lego after welding steel

Create variables
#

>> c = 3

c = 3
>>

Put the variable on the left of = sign You may add a semicolon ; to prevent the console from outputing your variables

>> c = 3;
>>

Entering data for matrices
#

>> A = [1 x; 8 -7]
A =
    1   x

    8   -7

which means

$$ A=\begin{bmatrix} 1 & x \\ 8 & -7 \end{bmatrix} $$

List the row vectors, separated by semicolons ;

Modifying matrix data
#

Editing single entry

>> A(1, 2) = 3

A =
    1   3
    8   -7

meaning to modify the element on the 1st row, 2nd column (Yes, matlab’s entries start from 1) to 3

Editing workspace On the top-right corner, there is a Workspace button, on which double click the Value entry column and a table will show up

Extracting entries
#

Extracting entry

>> A(1, 2)
ans = 
    3

Simply by A(row, column) you get a specific entry

Extracting column

>> v = A(:, 2)
v =
    3
    -7

Extracting row

>> v = A(2, :)
v =
    8   -7

Hint By the methods above, you can actually modify a whole row/column of matrix

Matrix Operations
#

(Answers are omitted)

Addition

>> A + C

Multiplication

>> A * C

Error will generate if the dimensions do not align

Transpose

>> A'

Workspace tips
#

  • Just like unix-like command-lines, pressing $\uparrow$ will show all the commands you have entered

  • Using the Command History window, you may copy the commands and modify your former commands

  • Using the Workspace on the top-right corner, you may modify any variables in current workspace

  • Importing an another .m file and its arguments in a subfolder

    >> addpath("path\to\folder\")
    
  • Use ; to separate commands on one line to fit in multiple commands in one line

  • Sometimes when a very small value was about to display in format rat mode, it displays as *

  • Clearing up workspace and workspace before and after script

    >> clc % clear command window
    >> clear % clear all variables
    >> % some work to do
    >> clear
    

Colon Operators
#

Usage Generate a row vector with equal size of lapse in space

Syntax

start : step_size : end

or

[start : step_size : end]
  • Start: The first element
  • Step size: As is, the step size each time start increments towards end
  • End: The largest element if attainable

Example

>> 2:8
ans = 
    2 3 4 5 6 7 8

Matrix function
#

eye(dimension)

>> eye(4)
ans =
    1   0   0   0
    0   1   0   0
    0   0   1   0
    0   0   0   1

Generate an identity matrix

ones(row, column)

>> ones(3, 2)
ans = 
    1   1   1
    1   1   1

Generate matrix with all ones

zeros(row, column)

>> zeros(3, 2)
ans =
    0   0   0
    0   0   0

Generate matrix with all zeros

diag(vector)

>> v = [1 2];
>> diag(v)
ans =
    1   0
    0   2

Generate diagonal matrix from the vector

Other matrix operations
#

Concatenate matrices

>> [zeros(2,2) ones(2,2)]
ans =
    0   0   1   1
    0   0   1   1

or

>> [zeros(2,2); ones(2,2)]
ans =
    0   0
    0   0
    1   1
    1   1

Incompatible dimensions raise an error

M-files
#

Instead of writing all commands in a window, you may write them in a .m file and then execute it

concatenate_test.m

A = [1 2; 3 4];
B = [1 3; 2 4];
C = [A ; B]

Switch to the same directory as concatenate_test.m

>> concatenate_test
C =
    1   2
    3   4
    1   3
    2   4

RREF(Gauss-Jordan Elimination) - rref(M) function
#

>> C = [1 1 1; 0 1 1];
>> rref(C)
ans =
    1   0   0
    0   1   1

Then you may solve for the equation

Plotting
#

scatter command
#

Func Plotting a set of points

Syntax

>> xvalues = [1:1:5];
>> yvalues = [1:1:5];
>> scatter(xvalues, yvalues)

Then you will see a picture of scattered points on x, y axis

hold command
#

Func Tell matlab not to generate an other plot individually, but to plot on the same axes

syntax

>> scatter(xvalues, yvalues)
>> hold on
>> fplot(@(x)exp(x), [1, 5])
>> hold off
>> fplot(@(x)sin(x), [1, 5])

Then you will see the same picture plotted with individual points and scatter, and an other trignometry graph elsewhere

fplot command
#

Func Draw a function’s plot

Syntax

>> fplot(func, interval)

where func is the function, and interval is the interval of the variable of the function.

  • You may write a function as (@x)<operations to x>, where @x tells matlab which variable to do with.
  • You may write an interval as [a, b], where a and b are lower bound, upper bound respectively.

Formatting output - format command
#

Use format to format your output numbers

Syntax

>> a = 1/2
a =
    0.5000
>> format rat
>> a = 1/2
a =
    1/2

where rat is abbreviation of rational, representing rational numbers

You may also use default to change back to decimals

Inverse - inv(M) function
#

Syntax

>> M = 2.*eye(2);
>> inv_M = inv(M)
inv_M =
    1/2   0
    0   1/2

Res ipsa loquitur

Hint If the inverse do not exist, the inverse will be a mix of inf - as the det is now 0, and division of 0 causes inf in matlab

Determinant - det(M)
#

Syntax

>> M = 2.*eye(2);
>> det_M = det(M)
det_M =
    4

Res ipsa loquitur

Declaration of function
#

function B=rowswap(M, i, j)
    % Here B is the return value
    tmp = M(i, :); % buffer
    M(i, :) = M(j, :); % set M's i's row
    M(j, :) = tmp; % set M's j's row
    
    % Set the return value to M, and it serves
    % as return
    B = M;

Res ipsa loquitur

Error raising - error(msg) function
#

function B=rowadd2(M, c, i, j)
    if(i==j)
        error('You cannot add a multiple of a row to itself')
        % Here the `error(msg)` function raises an error
    end
    M(j, :) = M(j, :) + c*M(i, :);
    B=M;

Res ipsa loquitur

Logic statements
#

function B=rowadd2(M, c, i, j)
    if(i==j) % Starting a logic statement
        error('You cannot add a multiple of a row to itself')
    end % Ending a logic statement
    M(j, :) = M(j, :) + c*M(i, :);
    B=M;

Res ipsa loquitur

Loops
#

For-loops
#

Syntax

for i = 1:1:10
    i
end

Result

i =
    1
i =
    2
...
i =
    10

Almost for i in range(xxx) in python i = 10 is inclusive as 1:1:10 naturally includes i = 10

Other functions
#

Absolute value - abs(x) function
#

Returns the absolute value

Syntax

>> x = [1 -2];
>> abs(x)
ans =
    1   2

Extreme value function - max(x) & min(x) function
#

Returns the coresponding extreme value in an array

Syntax

>> x = [1 -2];
>> max(x)
ans =
    1
>> min(x)
ans =
    -2

Random values - rand function
#

Func Generates a random value within 1 and 0, or random matrix

Syntax

>> rand
ans =
    0.0721
>> rand([1 2])
ans =
    0.0721  0.6324

3D Plots
#

Setting commands
#

Rotating - rotate3d A universal setting command. When types rotate3d on, we get a graph that can be rotated in 3d

Putting grids - grid A universal setting command. When types grid on, we get a graph with grids

Plotting multiple graphs in one plot - hold A universal setting command. When types hold on, any preceding graphs are plotted on the same plot

plot3 command
#

Syntax

z = 0:0.1:1000;
x = cos(z);
y = sin(z);
plot3(x, y, z);

Then it plots a sping-like graph

Interpretation of the code above

  • It prints the points one by one
  • It connects adjacent (in terms of the large array) using a line

Other syntax

plot3(x, y, z, 'mx-');
% Plots in 3D margaret, connected by straight lines, and marked each point with cross

Graph-related terms #

Shearing
#

In a fixed direction, points are displaced with an amount proportional to their signed distance on a given line parallel to that direction

Mathematically, when we are saying “a graph is sheared in y-direction with factor -2”, it means we are essentially adding the (-2) multiple of y-component to x-component, which is essentially achieved by multiplying a shear matrix, in this case,

$$ \text{Shear matrix} = \begin{bmatrix} 1 & 0 \\\\ -2 & 0 \end{bmatrix} $$

Dimensions of matrices
#

Rank calculation - rank(M) function
#

Func rank(M) calculates the rank of a matrix

Syntax

>> A = eye(3);
>> rank(A)
ans =
    3

Basis of kernel calculation - null(A, 'r') function
#

Syntax

>> A = [1 2 -4;
        2 -1 7;
        1 0 2];
>> ans = null(A, 'r')
ans =
    -2
    3
    1

If the nullity is zero, then null() will return an empty matrix with no columns

Eigenthings - eig(A)
#

Func To calculate the eigenvalues and eigenvectors

Syntax

[P, D] = eig(A);
P
D
  • P represents a matrix where its columns are eigenvectors
  • D represents a diagonal matrix where its diagonal entries are eigenvalues corespondingly to eigenvectors

Sum things up - sum(w) function
#

Syntax

w = [1 2 3];
sum(w)

Then we get 6. It sums all the entries in w

Vector products
#

Dot product - dot(u, v)
#

Syntax

>> u = [1 0 0];
>> v = [0 1 0];
>> t = dot(u, v)
ans =
    0

Cross product - cross(u, v)
#

Syntax

>> u = [1 0 0];
>> v = [0 1 0];
>> t = cross(u, v)
ans =
    0   0   1

Length of a vector - norm(v) function
#

>> u = [1, 1];
>> norm(u)
ans =
    1.4142