How to program with Matlab (PART 1/3)

Similar documents
Introduction to MatLab. Introduction to MatLab K. Craig 1

Module 1: Introduction RStudio

Introduction to Matlab for Econ 511b

Lab: Supplying Inputs to Programs

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

CITS2401 Computer Analysis & Visualisation

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

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

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

ECE Lesson Plan - Class 1 Fall, 2001

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

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

APPM 2460 Matlab Basics

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

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

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

Computer Vision. Matlab

An Introduction to MATLAB See Chapter 1 of Gilat

Getting To Know Matlab

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

Mathworks (company that releases Matlab ) documentation website is:

General Information. There are certain MATLAB features you should be aware of before you begin working with MATLAB.

Chris Simpkins (Georgia Tech) CS 2316 Data Manipulation for Engineers Python Overview 1 / 9

EGR 111 Introduction to MATLAB

Introduction to MATLAB

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

MAT 275 Laboratory 1 Introduction to MATLAB

A Basic Guide to Using Matlab in Econ 201FS

CS/NEUR125 Brains, Minds, and Machines. Due: Wednesday, March 8

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning.

ENGR 1181 MATLAB 05: Input and Output

CS1110 Lab 1 (Jan 27-28, 2015)

Introduction to Scientific Computing with Matlab

This book is about using Visual Basic for Applications (VBA), which is a

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

MATLAB TUTORIAL WORKSHEET

Arduino IDE Friday, 26 October 2018

MATLAB. Devon Cormack and James Staley

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

MATLAB Project: Getting Started with MATLAB

MATLAB Project: Getting Started with MATLAB

Bioinformatics? Reads, assembly, annotation, comparative genomics and a bit of phylogeny.

I OFFICE TAB... 1 RIBBONS & GROUPS... 2 OTHER SCREEN PARTS... 4 APPLICATION SPECIFICATIONS... 5 THE BASICS...

MATLAB Part 1. Introduction

Introduction to MATLAB

Why use MATLAB? Mathematcal computations. Used a lot for problem solving. Statistical Analysis (e.g., mean, min) Visualisation (1D-3D)

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Python Programming Exercises 1

MATLAB Introduction to MATLAB Programming

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

John's Tutorial on Everyday Mathcad (Version 9/2/09) Mathcad is not the specialist's ultimate mathematical simulator

Matlab Review. Dr. Mark Glauser, Created by: David Marr. Mechanical Engineering Syracuse University. Matlab Review p.

Computer Concepts for Beginners

Lab 1: Getting started with R and RStudio Questions? or

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

Thursday, February 16, More C++ and root

Introduction to MATLAB

Topics. Hardware and Software. Introduction. Main Memory. The CPU 9/21/2014. Introduction to Computers and Programming

Engineering Innovation Center MATLAB Basics

Introduction to Matlab

Formulas and Functions

Introduction to Matlab

Tutorial 1: Unix Basics

Chapter 1 Introduction

The first thing we ll need is some numbers. I m going to use the set of times and drug concentration levels in a patient s bloodstream given below.

Chapter 1: An Overview of MATLAB

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

LAB 2 VECTORS AND MATRICES

Digital Image Processing

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

Matlab Tutorial and Exercises for COMP61021

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

MATLAB Introductory Course Computer Exercise Session

Introduction to Matlab

This is a book about using Visual Basic for Applications (VBA), which is a

Introduction to Stata - Session 1

Week - 01 Lecture - 04 Downloading and installing Python

Microsoft Office 365 includes the entire Office Suite (Word, Excel, PowerPoint, Access, Publisher, Lync, Outlook, etc ) and an OneDrive account.

Introduction to Mathcad

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Reference Guide. Adding a Generic File Store - Importing From a Local or Network ShipWorks Page 1 of 21

Formulas, LookUp Tables and PivotTables Prepared for Aero Controlex

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Getting Started with Amicus Document Assembly

Dr Richard Greenaway

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

MATLAB BASICS. M Files. Objectives

Matlab- Command Window Operations, Scalars and Arrays

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

Computer Project: Getting Started with MATLAB

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Course contents. Overview: Goodbye, calculator. Lesson 1: Get started. Lesson 2: Use cell references. Lesson 3: Simplify formulas by using functions

EL2310 Scientific Programming

Introduction to MATLAB

Dr Richard Greenaway

TUTORIAL MATLAB OPTIMIZATION TOOLBOX

Transcription:

Programming course 1 09/12/2013 Martin SZINTE How to program with Matlab (PART 1/3) Plan 0. Setup of Matlab. 1. Matlab: the software interface. - Command window - Command history - Section help - Current directory - Workspace - Editor - Set Path 2. Rules and conventions of the programming language of Matlab. - Variables - Vector and matrix - Indexing or subscripts - Calculation - Relational and logical operators - Two other possible structures - Flow controls - Creating a function - Programming conventions 3. Basic graphs with Matlab. - Plot - Subplot - Barplot et histograms 0. Setup of Matlab Matlab is multi-platform software existing for any types of operating systems (OS: Mac, PC 32 bits, PC 64 bits, Linux). You are kindly invited to setup a version corresponding to your OS for example by asking the administrator of your laboratory or of your University. Be careful to setup the software corresponding to the specificity of your computer, setup either the 64 or 32 bits of Matlab. If you encounter problems during the setup, feel free to ask me questions (martin.szinte@gmail.com).

Remark: You are certainly not the only one to encounter problems during the setup of Matlab, don t hesitate asking questions or checking on Internet if anyone has the same problem and maybe solutions. 1. Matlab: the software interface Matlab is a complex software, composed of several windows that you can arrange in size, position, and that you can make appear or disappear as desired you can then organize the software in function of your tastes and needs. I will describe in the following chapter the windows you might need. Command window: We will use this window to communicate to Matlab any simple codes that you do not want to save. 1+1 factor(24) cosd(90) cosd(0) This window will serve us for doing simple processing. This is also in this window that error message will be displayed (due to one or several errors in your codes or little programs). This error message will be essential for our progress in programming. cos(32,5) -> An error message appears in command window indicating that the function cos doesn t take two arguments. We will see soon what an argument is but for the moment, this example allow us to illustrate the type of error message that Matlab reports. Command history: As indicated by its name, this window allow us to find back the different codes typed earlier in the command window, that is the history of our actions

Advice: You can recover the last typed command using the keyboard up arrow when your cursor is in the command window. Help section: This section is certainly the reason why Matlab is today the most used programming software in Sciences. Indeed, Matlab possesses a highly developed database on a huge set of functions and toolboxes that it contains. Moreover Matlab integrates a powerful search engine as well as a complete online help database with tons of examples and codes to download. Therefore with more or less time any initiated user can learn how to use new functions and toolboxes, learning by himself/herself via this help section and its definitions and concrete examples. There are different ways to access the help of Matlab: 1. Button Help: you must click on the button? 2. Type help in the command window. 3. Type help + function name help cos => it gives you help on a specific à function such as cosinus. 4. Type a particular function, select it then using the secondary mouse button choose Help on selection. => If the function is a Matlab function (made by the firm), this manipulation will send you to the help navigator. If it is a home made function, the help navigator will send you to the initial comment you have type when the function was created (we will go back to that point when we will speak of the programming conventions to use when creating new functions). Help Navigator. - Useful section as you will generally found well-stated explanations. - Propose some definitions of concepts, courses on some points (as in statistics), syntax and concrete examples on functions. - In the case of a specific search, the help navigator frequently report a definition of the function. For example have a look at the function cos.

Advice: It could be useful to have a look at the end of the help navigator window where you will find the see also section. You will find others functions that might better correspond to your needs. Current directory/folder This window indicates the directory of reference in which Matlab executes the functions. It also is the directory where new pieces of code, new data tables or texts will be saved by default (via saving functions such as csvwrite). csvwrite('tab.csv',[1 2 3 4 5 6 7]) The function csvwrite create CSV files, CSV for comma-separated values, which is a common format for saving numerical values. Here the code saves the values [1 2 3 4 5 6 7] in a file called tab.csv, which will be stored in the current directory. Advice: We can easily modifies the current directory using the function cd cd C:/your file /tatata/tatati %(for PC) cd /your file/tatata/tatati %(for mac) Type help cd for more information. Workspace This window contains a description of all the variables typed in the command window or in a script. As suggested by its name, it is the working memory of the software. We will then use this window for example to check that a variable exists and that its value corresponds to the expected one. If you type cat = 32 in the command window, the new variable cat appears in the workspace, as well as its values, its minimum and maximum (note that using the secondary

mouse button you can select the variable information you want to display in the workspace window. Advice: It might be useful when a variable contains a lot of different values (lot of columns and rows) to visualize these in a table. By double-clicking on elements of the workspace, you can access to the array editor window. This window displays your variable as (for example) in Microsoft Excel. It is even possible to modify a value of the table and to enter new values (for example with copy/paste from a table in Microsoft Excel). Editor This last window allows us to create and edit.m files (and others). After clicking on the editor window, click File >> New > and choose M-File. An empty page appears in the editor window. Write on the page the following things: text = I just wrote my first program with Matlab ; disp(text) Now save your script File>>Save as, under the name start.m. That.m file will be saved in the current directory as explained previously. Now that your new script (or new little program) is saved, you can close and re-open it as desired. You can also execute the script by clicking on the green arrow in the editor or by pressing F5 on the keyboard). The script will then displayed in the command window: I just wrote my first program with Matlab Advice: Open a new.m file and put in it all the different lines of code that we will see and have seen so far. Name this file for example course_matlab_nb1.m. You will then have a record of all the things we have seen here in a single file from which you can easily execute the codes. You can then comment each code, using %. This simple letter will tell Matlab that the following is a comment and should not be executed.

Set Path In the section File you can find the sub-section Set path. When you click on Set path a window will appear that allows you to manage all functions and toolboxes path. Then, each time we will create a script (program without input nor output) or a function (program with input and output), we will need to specify its path so that Matlab executes it. For this purpose, you have 3 different solutions: 1. Change the current directory and put all your function and scripts in this directory, which will become then the default directory. 2. Add each directory of your functions and scripts using the set path window, and clicking on Add Folder or Add folder with sub folder and selecting your directory. 3. Use at the beginning of your codes the Matlab function addpath() and specify the directories for which you would like to create a path (for more information help addpath). Advice: If you use the solution 1 or 2, never called two programs with the same name. Indeed Matlab will choose one of the two functions (the latest recorded in the path) and it might then not be the one you want. The solution 3 is from far the best solution as the path is added every time you launch a program. With this solution you do not have to take up to date the path list. Also you will be able to launch your programs several months or years after their creation without the need to remember the important directories to add to the path before starting a program. 2. Rules and conventions of the programming language of Matlab Matlab uses a particular language so-called high level (to differentiate form the low level languages also called machine language), which is also a script language, meaning that it allows the avoidance of compiling the program (a long step that involve the transformation of a source code readable by human to a binary file executable by a machine).

Therefore a program made in Matlab is easily understandable and the learning of the language is far more rapid. A counterpart of this accessibility is that Matlab is slower than any other compiled language program as it needs to be interpreted every time it is launched. As any script language, Matlab language involves several rules and conventions allowing respectively the program to correctly works and the better understanding of a program when it is shared between different peoples. Indeed, it exists several ways of programming the same experience or the same analyses of data. The following course describes a way of doing it and one type of conventions. Feel free to modify the codes to fit your way of thinking and of programming. As soon as a program works the code behind doesn t matter. VARIABLES We will start here with the basis of programming with Matlab, which is the creation of variables. You can attribute a value to an element and store it in the working memory to be able to use it later in a calculation or another execution. For this purpose you should type for example: str1 = 'I have no clue of what I am currently doing' With this statement, we just said to the software to create a variable called str1, which is a list of characters (a string). Type now: a = 7 b = 5; a+b; a+b Question 1: What happens in the command window? What s the point of using a semi-colon? Without semi-colom, the command window returns the /value of a or the results of a+b. When the semi-colon is typed after the command, nothing is displayed in the command window.

The semi-colon allows us to avoid the display of all the calculations; nevertheless the calculations and creation of variables still occur even though nothing is printed in the command window. Type: c = a+b; c You can notice that c has for value the sum of a+b even if the results is not displayed first. Remark: Sometimes Matlab will be stuck during the execution of a calculation, even though nothing is printed in the command window (you will then see busy at the lower left corner of Matlab). Under such situation, you can stop the current calculation by pressing CTRL + C. Type now: who whos The function who returns a list of variable stored in the workspace. The same list is accessible directly in the workspace window. Question 2: What s the role of whos? Whos returns the same list of the workspace, but this time with more details (size of the variable, memory allocated and class of the variable). You can then notice that str1 is a char class, a, b, c are double class. Indeed in function of how we code these different variables (using quotation marks for str1 and nothing for the others), Matlab understands that str1 is a list of characters and attributes the then the class «char». a, b and c involve a number or the results of a calculation as values, Matlab attributes then the class «double» for double-precision floating point (one way of coding numbers in informatics). VECTOR ET MATRICES Vectors and matrices are the basis of Matlab programming, which is indeed called Matlab for MATrix LABoratory.

Whatever the type of data that you with to treat with Matlab, it will be necessary for you to think and to reason in terms of matrices of either one dimension (=vectors) or 2 or more dimensions (matrices). In order to create a vector you then need to type: rawvect1 = [1, 2, 3, 4, 5, 6]; rawvect2 = [1:6] ; Question3: What s the reason of using : when creating our new vector rawvect2? The notation rawvect2 = [1:6]; orders to Matlab to create a vector identical to rawvect1. Indeed in Matlab the two dots indicates until. We will then go from 1 until 6 and by default the steps will always be 1. Question4: How can we go from 1 to 6 by a different step than 1, for example by step of 2? rawvect3 = [1:2:6] ; In order to create a vector in column we can type: colvect1 = [1; 2; 3; 4; 5; 6]; colvect2 = rawvect1 We use then semi-colon to separate the different values. The apostrophe allow us to put the values in a single column. Question5: How can we create a variable with two columns or more? mat1 = [1, 2; 3, 4; 5, 6; 7, 8] mat2 = [1, 2, 3; 1, 2,3 ; 1, 2, 3 ; 1, 2, 3] mat3 = [1, 2, 3; 4, 5, 6 ; 7, 8, 9 ; 10, 11, 12]

INDEXING OR SUBSCRIPTS Each variable that we defined earlier (char, vectors and matrices) have a certain size corresponding to the number of rows and columns they are composed of. In order to access the size, type: size(mat1) size(str1) numel(str1) length(mat2) The function size() send back the number of rows and columns of a variable. To access one, several or all the elements of a variable, type: rawvect1(1) rawvect1(2) rawvect1([1 2 4]) rawvect1(1:2) rawvect1(:) In this situation the operator : means all. str1(10:end) For a matrix containing several lines and columns we will type: mat3(1,3) mat3(3,3) Question 6: What are the index numbers of the word «no» of the variable str1? str1 = 'I have no clue of what I am currently doing' If you type str1(8) you will notice that the n or the word no is the 8 th element of that variable and not the 6 th element. Indeed Matlab considers a space as a distinct element.

Question 7: How can we obtain the second line of the variable mat3? The 3 rd column? The two last lines? mat3(2,:) mat3(:,3) mat3(end-1:end,:) You can also modify one or several elements of a variable using the same indexing: mat3(1) = 2 mat3(:) = 2 str1 = ' I have no clue of what I am currently doing'; str1([3:15]) = 'have a clue'; Question 8: Why this last command doesn t work? You will have to replace each element by a new element, as there are 13 elements called, you should then type 13 elements in your new chain of characters. We will then for example: str1([3:16]) = ' have a clue '; (with two spaces, one before and one after the text! )