0% found this document useful (0 votes)
75 views23 pages

Introduction To MATLAB Programming: Fundamentals: Shan He

This document provides an introduction to MATLAB programming, covering topics such as matrix operations, programming fundamentals, and plotting. It explains that MATLAB is a numerical computing environment and programming language used widely in science and engineering. It allows for fast matrix operations and contains mathematical and visualization functions. Programming in MATLAB can be done through scripts or custom functions.

Uploaded by

a s prakash rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views23 pages

Introduction To MATLAB Programming: Fundamentals: Shan He

This document provides an introduction to MATLAB programming, covering topics such as matrix operations, programming fundamentals, and plotting. It explains that MATLAB is a numerical computing environment and programming language used widely in science and engineering. It allows for fast matrix operations and contains mathematical and visualization functions. Programming in MATLAB can be done through scripts or custom functions.

Uploaded by

a s prakash rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction to MATLAB programming

Introduction to MATLAB programming:


Fundamentals

Shan He

School for Computational Science


University of Birmingham

Module 06-23836: Computational Modelling with MATLAB


Introduction to MATLAB programming
Outline

Outline of Topics

Why MATLAB?

Matrix operations in MATLAB

Programming in MATLAB

Plotting in MATLAB
Introduction to MATLAB programming
Why MATLAB?

What is it?

I A humble origin: an interactive matrix calculator for students.


I Now more than 1 million users
I Used in engineering, science, and economics, etc.
I ”A high-level technical computing language and interactive
environment for algorithm development, data visualization,
data analysis, and numerical computation.” – Matworks
Introduction to MATLAB programming
Why MATLAB?

Key features

I ”High-level language for technical computing.”


I ”Mathematical functions for linear algebra, statistics, Fourier
analysis, filtering, optimization, and numerical integration.”
I ”2-D and 3-D graphics functions for visualizing data.”
I ”Interactive tools for iterative exploration, design, and
problem solving.”
Introduction to MATLAB programming
Why MATLAB?

Why MATLAB?

I Concise matrix notation and great matrix manipulation.


I Easy visualisation.
I Many useful “toolboxes” and great community support.
I Great tool for computational modelling and data analysis.
Introduction to MATLAB programming
Why MATLAB?

A tour to MATLAB
Introduction to MATLAB programming
Matrix operations in MATLAB

The most useful command in MATLAB

>> help
Introduction to MATLAB programming
Matrix operations in MATLAB

The heart of MATLAB: matrices

I MATLAB stands for “matrix laboratory”.


I The basic data type is matrix (including vectors).
I Matrix operations: create, access, modify and manipulate
matrices
I Matrix operation is very fast in MATLAB – try to avoid
for-loops
Introduction to MATLAB programming
Matrix operations in MATLAB

Creating Matrices

I Create an empty matrix:


>> A = []
I Enter data directly:
>> A = [1 1; 2 3; 4 5]
I If you know the pattern of your matrix:
>> A =[1:2:100]
I A lot of functions to create specific matrices: zeros(),
ones(), rand(), eye()
I Click here to download an example.
Introduction to MATLAB programming
Matrix operations in MATLAB

Transposing and concatenating matrices

I To transpose matrix A, use the transpose operator ’


>> B = A’
I To concatenate matrix, enclose them inside of square brackets.
>> C = [A; 6 7]
Introduction to MATLAB programming
Matrix operations in MATLAB

Indexing
I To extract individual entries from a matrix, use indices inside
round brackets:
>> A(1,2)
I Use the ‘:’ operator to extract all entries along a certain
dimension:
>> A(1,:)
I Use ‘end’ statement to get the last index of a dimension:
>> A(end,1)
I Use logical indexing to find specific entries:
>> A(A>2)
I We can also use find() function to find specific entries:
>> A(find(A>2))
Introduction to MATLAB programming
Matrix operations in MATLAB

Assignment and deletion

I To change entries in the matrix, using indexing to specify the


entries and assign new values:
>> A(1,2) = 100
>> C(:, 1:2:end) = 500
I To delete entries, assign ‘[]’ :
>> A(1,:) = []
I For a matrix, you can only delete column(s) or row(s)
I For array (1D matrix), you can delete any entries.
>> B(3) = []
Introduction to MATLAB programming
Matrix operations in MATLAB

Reshaping and Replication

I We can reshape an array of size m-by-n to size p-by-q by


reshape()
>> A = rand(2,3)
>> reshape(A, 1, 6)
I We can also tile an array m-by-n times using repmat()
function:
>> A = rand(2,3)
>> repmat(A, 1, 6)
Introduction to MATLAB programming
Matrix operations in MATLAB

Matrix manipulations

I We can perform matrix addition, subtraction, multiplication,


exponentiation, etc.
I For example, matrix multiplication of an m-by-n matrix and
an n-by-p matrix yielding an m-by-p matrix:
>> A = rand(3,3)
>> B = rand(3,3)
>> C = A*B
I We can do element-wise matrix arithmetic by using ‘.’ precede
the arithmetic operator
>> D = A.*B
I For element-wise arithmetic operation, both matrices must be
the same size.
Introduction to MATLAB programming
Matrix operations in MATLAB

Matrix manipulations

I We can also do matrix division, but be aware of Matrix


Right Divide / and Matrix Left Divide \
>> C = A*B
>> Alsq = C/B
>> Blsq = A \ C
I Note that C/B is equivalent to (B’\ C’)’ and A\ C is
equivalent to inv(A)*C
Introduction to MATLAB programming
Matrix operations in MATLAB

Sparse Matrices

I If we have a large matrix but containing many zeros, it is


better to convert it to a sparse matrix:
>> A = zeros(1000,1000);
>> A = sparse(A);
I We can use sparse matrices just like ordinary matrices but
slower:
>> A(10,10)=1;
>> B = rand(1000,1000);
>> C=A*B;
I We can always convert sparse matrices to full matrices.
>> A = full(A);
Introduction to MATLAB programming
Programming in MATLAB

Flow of Control

MATLAB only has the following statements:


I if, else, elseif
I switch statements
I for loops
I while loops
I try/catch statements
Introduction to MATLAB programming
Programming in MATLAB

Scripts and functions


I We can use MATLAB editor to edit/save/load/exceute your
programs.
I Two types of MATLAB programs: scripts and functions.
I A script is a collection of Matlab commands.
I The commands in the script are executed exactly as at the
command prompt.
I However, scripts:
I No lexical scoping, that is, the variables in scripts are global.
We cannot reuse the same variable name multiple times.
I Cannot be parameterize to be called multiple times with
different inputs.
I Difficult to read and understand.
I Slow.
Introduction to MATLAB programming
Programming in MATLAB

Creating functions
I Open a new file in MATLAB editor, or type: edit
filename.m at the command prompt.
I In you m file, begin by creating the function header:
function [output1 ,output2, output3...] =
myfunction(input1, input2...)
I We can use the inputs as local variables.
I All variables are local in a function.
I We must assign values to each of the outputs before the
function terminates.
I Although optional, it is better to end the function with the
“end” keyword
I Let’s see an example (download from here).
Introduction to MATLAB programming
Programming in MATLAB

Functions: other issues

I The functions must located in the directories of the command


path, or under the current working directory.
I Use “%” for comments
I We can have multiple functions in a .m file
I We can pass functions as inputs to other functions by creating
handle to the function and then pass the handle as a variable.
>> x = fminbnd(@humps, 0.3, 1)
I We can create anonymous functions without having to store
your function to a file each time: fhandle = @(arglist) expr.
For example:
>> sqr = @(x) x.*x;
Introduction to MATLAB programming
Plotting in MATLAB

1D/2D plots

I To plot 1D and 2D data, we use plot(y).


I If y is a vector: a piecewise linear graph of the elements of y
versus the index of the elements of y
I If y is a matrix: plot(y) will automatically cycle through a
predefined (but customizable) list of colors to allow
discrimination among sets of data
I If we specify two vectors as arguments, plot(x,y) produces a
graph of y versus x.
I Use hold on command to superimpose all the plots onto the
same figure. Use hold off to disable.
Introduction to MATLAB programming
Plotting in MATLAB

3D plots

I To plot 3D lines: plot3(X1,Y1,Z1)


I To plot 3D shaded surface: surf(X,Y,Z)
I You can also specified shading property: shading
flat/faceted/interp
I To plot 3D mesh: mesh(X,Y,Z)
I To plot contour lines: contourf(X,Y,Z)
I Download my example at here
Introduction to MATLAB programming
Plotting in MATLAB

Customise plots

I Multiple subfigures: subplot(nr,nc,i)


I Title: title(’you title’)
I Axis labels: xlabel(’x’); ylabel(’y’); zlabel(’z’)
I We need to get handle of a figure
I Handle of the current figure: gcf()
I Handle of the current set of axis: gca()
I To access specific properties: get(handle,’property’)
I To change specific properties: set(handle,’property1’,
value1, ’property2’, value2, ...)

You might also like