Some elements for Matlab programming

Similar documents
Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

A Guide to Using Some Basic MATLAB Functions

MATLAB and Numerical Analysis

Matlab course at. P. Ciuciu 1,2. 1: CEA/NeuroSpin/LNAO 2: IFR49

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

Lecturer: Keyvan Dehmamy

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

MATH 3511 Basics of MATLAB

Fundamentals of MATLAB Usage

Chapter 1 MATLAB Preliminaries

MATH 5520 Basics of MATLAB

2.0 MATLAB Fundamentals

Introduction to MatLab. Introduction to MatLab K. Craig 1

Introduction to Matlab

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

CDA5530: Performance Models of Computers and Networks. Chapter 8: Using Matlab for Performance Analysis and Simulation

Matlab Tutorial, CDS

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Matlab Workshop I. Niloufer Mackey and Lixin Shen

A General Introduction to Matlab

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Getting started with MATLAB

Entering the numbers in these two ways creates the same matrix A.

CDA6530: Performance Models of Computers and Networks. Chapter 4: Using Matlab for Performance Analysis and Simulation

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

Chapter 2. MATLAB Fundamentals

CDA6530: Performance Models of Computers and Networks. Chapter 4: Using Matlab for Performance Analysis and Simulation

Introduction to Scientific and Engineering Computing, BIL108E. Karaman

short-reference.mht 1/ /WK/

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Introduction to MATLAB

A very brief Matlab introduction

Introduction to MATLAB

Learning from Data Introduction to Matlab

Introduction to GNU-Octave

Introduction to MATLAB Practical 1

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Introduction to MATLAB

Introduction to MATLAB

AN INTRODUCTION TO MATLAB

An Introduction to MATLAB II

Introduction to Matlab

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

A Quick Tutorial on MATLAB. Zeeshan Ali

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

Lecture 2: Variables, Vectors and Matrices in MATLAB

A QUICK INTRODUCTION TO MATLAB

What is MATLAB and howtostart it up?

Matlab and Octave: Quick Introduction and Examples 1 Basics

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Introduction to MATLAB LAB 1

Introduction to MATLAB

Getting Started with MATLAB

Computational Mathematics

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

MATLAB Introductory Course Computer Exercise Session

Matlab and Psychophysics Toolbox Seminar Part 1. Introduction to Matlab

1 Introduction to MATLAB

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

Introduction to MATLAB Programming

Programming in Mathematics. Mili I. Shah

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

University of Alberta

MATLAB Workshop Dr. M. T. Mustafa Department of Mathematical Sciences. Introductory remarks

TUTORIAL 1 Introduction to Matrix Calculation using MATLAB TUTORIAL 1 INTRODUCTION TO MATRIX CALCULATION USING MATLAB

MATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017

PART 1 PROGRAMMING WITH MATHLAB

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

A = [1, 6; 78, 9] Note: everything is case-sensitive, so a and A are different. One enters the above matrix as

McTutorial: A MATLAB Tutorial

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Arithmetic and Logic Blocks

Matlab Tutorial and Exercises for COMP61021

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Getting Started with MATLAB

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Introduction to Matlab

An Introductory Tutorial on Matlab

MATLAB GUIDE UMD PHYS401 SPRING 2012

Introduction to MATLAB 7 for Engineers

Consider this m file that creates a file that you can load data into called rain.txt

Octave Tutorial Machine Learning WS 12/13 Umer Khan Information Systems and Machine Learning Lab (ISMLL) University of Hildesheim, Germany

Laboratory 1 Octave Tutorial

INTRODUCTION TO MATLAB PROGRAMMING Lec 1.1: MATLAB Basics

LAB 1 General MATLAB Information 1

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

CSCI 6906: Fundamentals of Computational Neuroimaging. Thomas P. Trappenberg Dalhousie University

Introduction to Matlab. High-Level Computer Vision Summer Semester 2015

Introduction to MATLAB for CSE390

Chapter 1 Introduction to MATLAB

Scientific Computing Lecture 1: MATLAB fundamentals

HERIOT-WATT UNIVERSITY DEPARTMENT OF COMPUTING AND ELECTRICAL ENGINEERING. B35SD2 Matlab tutorial 1 MATLAB BASICS

Built-in Types of Data

Introduction to MATLAB

Transcription:

Some elements for Matlab programming Nathalie Thomas 2018 2019 Matlab, which stands for the abbreviation of MATrix LABoratory, is one of the most popular language for scientic computation. The classical applications of Matlab are : mathematical computation, algorithm development, model establishment and simulation, data analysis and virtualization, and user interface design. 1 Help commands There are some very useful instructions thereafter : lookfor keywords allows one to nd a command with the help of keywords. Example : lookfor filter. Matlab will return the list of functions whose tutorials contain this keyword. help command returns a tutorial on the required command. Contrary to lookfor, one should provide the exact command name. Example : help mean. help toolbox returns all the commands which belong to the required toolbox. Example : help signal; help stats; help optim; help nnet;. 1

2 Matrix 2.1 Construction Matlab mainly deals with matrix computations. Vectors or scalars are considered as a single row and/or a single column matrix. There are many dierent ways to dene a matrix : it can be dened by one list of elements, it can be generated dynamically using functions, or it can also be loaded from a le. The denition by a list of elements can be presented as follows : A = [1 2 3; 4 5 6; 7 8 9] This instruction will dene a 3 3 matrix and assign it to the variable A. The elements of the same row are separated by spaces or by commas, while dierent rows are separated by semicolons. Matlab can also deal with complex matrices : A = [1 2; 3 4] + i [5 6; 7 8] A = [1 + 5 i 2 + 6 i; 3 + 7 i 4 + 8 i] i or j can be used as the imaginary unit without any dierence. If they have been already used as variables, one can redene the imaginary unit : ii = sqrt( 1) The way that matrix elements are indexed can be resumed as follows : A(2, 3) is the element of the second row and third column of the matrix A. For a vector B, B(4) is the fourth element of the vector, whatever B is a row vector or a column vector. Be careful the index of element begins with 1 (not 0!!!). One can assign a scalar to one element of a matrix as follows : A(2, 4) = 8 This instruction will assign the value 8 to the element at the second row and the fourth column of the matrix A. 2

Some functions exist to create a matrix. The most commonly used are : zeros : matrix of zeros ones : matrix of ones eye : identity matrix linspace : arithmetic progressed vector logspace : logarithmic progressed vector diag : create or extract the diagonal of a matrix For example, zeros(m,n) create a m n matrix of zeros, and zeros(n) create a n n matrix of zeros. If x is a vector, diag(x) is a diagonal matrix whose diagonal elements are the elements of x (remaining elements are zeros). If A is a square matrix, diag(a) is a vector that contains the diagonal elements of A. A matrix can be also be dened by blocks. Given A a 3 3 matrix : will dene a 5 5 matrix. B = [A, zeros(3, 2); zeros(2, 3), eye(2)] Random number generator (use help stats to see the list) allows one to generate matrices whose elements follow a given distribution. For example, the command rand(n) creates a n n matrix whose elements follow the uniform distribution between 0 and 1. rand(m,n) creates a m n matrix whose elements follow the same uniform distribution. The command randn(n) creates a n n matrix whose elements follow a Gaussian distribution of mean 0 and variance 1. randn(m,n) creates a m n matrix whose elements follow the same Gaussian distribution. The notation : allows one to exploit the matrix structure of Matlab and to save loops compared with many other programming languages. For example 1:5 is the row vector [1 2 3 4 5]. Of course, the step of incrementation can be a non integer, the syntax is then start : step : (by default, the step is equal to 1). Example : 0.2:0.2:1.2 is the vector [0.2 0.4 0.6 0.8 1.0 1.2], and 5:-1:1 is [5 4 3 2 1]. 3

The notation : also allows to reach a submatrix of a given matrix. For example, A(1:4,3) is the vector composed of the rst 4 elements of the 3 rd column of the matrix A. A(:,3) is the 3 rd column of the matrix A and A(1:4,:) is composed of the rst 4 rows of A. It also permits to replace some parts of a matrix. For example, A(:,[2 4 5]) = B(:,1:3) replace the column 2, 4 and 5 of A by the rst 3 columns of B. The function reshape(a,m,n) reconstructs the matrix A with m rows et n columns. 2.2 Elementary operations Following operations are available in Matlab : + addition conj conjugate only subtraction. transpose only multiplication \ left division ˆ power / right division conjugate transpose These commands can be used on matrices but also with scalars. If the dimensions of matrices are not compatible, one error message will appear, except when one operation between a scalar and a matrix is computed (the operation will be achieved between the scalar and each element of the matrix). Warning : The matrix division is particular. Given A a matrix and b a row or column vector, x=a/b is the solution of xa=b. The left and right division are related by b/a = (A'\b')'. In order to solve this, Matlab calculates the inverse of A when A is invertible (its pseudo-inverse when A is singular) without any warnings. 2.3 Element by element operations Classical operations, like, ^, \, / can also be used element by element on a matrix or a vector by adding a dot before the operation symbol. For example : [1 2 3 4].*[1 2 3 4] or [1 2 3 4].^2 give [1 4 9 16]. 4

2.4 Elementary functions In Matlab, the common elementary functions used on matrices and vectors are : sin, cos, tan,asin, acos, atan sinh, cosh, tanh, asinh, acosh, atanh exp, log, log10 rem, abs, angle, real, imag, conj, sqrt, sign round, floor, ceil, fix Other functions give a scalar output when they take vectors as input. When we apply them on matrices, they operate on each column indepently. Therefore, the operation result is a vector. They are : max, min, sort, sum, prod, median, mean, std any, all For example, the maximal element of a matrix A is given by max(max(a)) (not by max(a) which returns a vector). 2.5 Matrix functions The most used functions are : eig eigenvalue poly det inv expm sqrtm size characteristic polynomial determinant inverse exponential matrix matrix square root size of array 3 Workspace management The following functions allow to have a global view of the workspace : who lists current variables whos what lists current variables, their dimensions and their types lists.m and.mat les The variables can be deleted using the command clear variable_name. Pay attention to the command clear which deletes all the variables within the 5

workspace. When leaving Matlab, all the variables are lost. It is possible to save them by using the command save file_name name_of_variables_to_save. The le format is then.mat. To reload variables, use load file_name. Some classical DOS or Unix commands also exist in Matlab : pwd shows the current working directory cd ls or dir what path changes the working directory lists all the les in a working directory lists the.m,.mat and.mex les in a working directory gets/sets search path The other DOS or Unix commands can be executed if they are preceded with!. Example :!del file_name. 4 Loops, tests and relations In Matlab, this type of functions operates similarly as those in C or Pascal language. But pay attention : Replace a loop by a matrix operation when it is possible, because this will reduce signicantly the computational time. 4.1 Loops The repeated execution of series of instructions can be achieved using for or while. The for loop syntax is as follows : for condition instructions For example, given n : x = [ ] for k = 1 : n %creates an empty vector x = [x k 2 ]; 6

The while loop syntax is as follows : while expression processing Processing will be repeated while the expression is true. The series of instructions to be executed can be constrained by conditions using the instructions case and otherwise. 4.2 Test : if instruction This instruction allows to execute series of conditional instructions. Its syntax is as follows : if condition instructions The processing will be executed only if the condition is true. Multiple cases are possible : if condition1 instructions1 elseif condition2 instructions else instructions 4.3 Relations The main relational operators are as follows : < smaller >= bigger or equal > bigger == equal ( = is an aectation) <= smaller or equal = dierent 7

They can be combined with the following logical operators : & and, or, not When a relation is applied to scalars, the result is then equal to 1 or 0 deping on whether it is true or false. When a relation is applied to matrices or to vectors with the same dimension, the result is a matrix whose elements are 1 or 0. A relation between matrices is interpreted by while and if as true if the condition is satised by all the elements of the matrix. Therefore, if you want to execute a processing when the matrices A and B are equal, you may do : if A = = B processing whereas if you want to execute a processing when they are not equal, if A = B processing will not return the expected result, because the processing will be executed only if all the elements of A et B are dierent. So you may write : or if any(any(a = B)) if A = = B else processing processing The functions any and all allow to solve the relations between matrices into vectors or scalars. The function find is also an interesting function : it returns the index of elements satisfying a condition. For example, given y as a vector, then find(y > 2) will return a row vector containing the index of the elements of y which are strictly bigger than 2. 8

4.4 Pause and break During the execution of a program, it is possible to susp its execution using the command pause. The execution will then continue by pressing any key. The command break stops the execution of a loop while or for. 5.m les Matlab can execute a set of instructions within a program. These programs are with the extension.m. There are two types of.m les : scripts and functions. % allows to insert comments. If the last character of an instruction is a semicolon, the output is not displayed. 5.1 Scripts A script le contains a set of Matlab instructions. If the name of a given le is prog.m, the command prog will execute it. The variables of a script le are global. The execution will change their values in the workspace. 5.2 Functions The variables of a function are local (but can be declared as global variables). The rst line of a function script should always be function [result1, result2,...] = file_name(argument1, argument2,...) Consider, for example, the function function y = mean(x) y = sum(x)/length(x); This function (saved as mean.m) computes the mean value of the elements in 9

vector x. It can be called from a.m le, for example like this : X = [1 2 3 4]; Average = mean(x); 5.3 Texts, inputs, error messages Texts should be in quotes : s = 'texte'. They can be displayed on the Matlab command window : disp( show ). Error messages can be displayed using the command error, which also stops the program at the same time : error( sorry! ). 5.4 Vectorization and pre-allocation To reduce the computational time of a program, it is important to vectorize algorithms in the.m le. In fact, Matlab can deal with matrix and vector operations instead of using loops as in other programming languages. Consider the following example : f0 = 0.2; for t = 1 : N y(t) = sin(2 pi f0 t) By vectorizing the program, it can be rewritten as : f0 = 0.2; t = 1 : N; y = sin(2 pi f0 t); When it is not possible to vectorize, it is necessary to pre-allocate the vectors or the matrices in which the results will be saved to make the loops faster. For example : y = zeros(1, 100); for (i = 1 : 100) y(i) = det(xˆi); 10

If you do not pre-allocate the vector, Matlab will refresh its dimension every loop, which is very time consuming. 6 Plots Matlab allows to display 2-D and 3-D plots. In order to have an idea of the graphical capability of Matlab, you can use the command demo but, for the signal (and also later for the telecommunication) practical work, we will essentially use 2-D plots. Given two vectors with same dimension, x and y. The command plot(x,y) will plot y as a function of x. If you want to plot a second graph in a new gure, insert the command figure or figure(i + 1) if the current gure is indexed by i. To plot several curves within the same gure, type hold on. This command can be canceled by hold off. The texts and/or labels on the axis or gures can be done using the following commands : title gure title xlabel X-axis label ylabel Y-axis label gtext places text with mouse text text annotation The command grid adds a grid on a gure. All the above commands should be typed after the command plot. By default, the curves are plotted in continuous lines, but there are other options :- -, :, -.,., +, *, o and x. Similarly, one can precise the colors using : y, m, c, r, g, b, w and k. For example, plot(x,y,'r*') will plot y as a function of x in red stars * or plot(x,y,'r-*') will plot y as a function of x with red stars * linked points. The command subplot allows one to divide one gure into several subgures : subplot(m, n, p) divides the gure window into a m n matrix of small subgures and select the p th sub-gure for the current gure. The commands semilogx and semilogy, instead of plot, allow to obtain semi-logarithmic axis. 11