MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Slides:



Advertisements
Similar presentations
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Advertisements

1 JavaScript: Control Structures II. 2 whileCounter.html 1 2
Programming with MATLAB
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Introduction to MATLAB
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Programming in MATLAB Week 14 – 4/28/09 Kate Musgrave
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 21P. 1Winter Quarter MATLAB: Structures.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
MATLAB Lecture One Monday 4 July Matlab Melvyn Sim Department of Decision Sciences NUS Business School
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
ENGR 1320 Final Review - Programming Major Topics: – Functions and Scripts – Vector and Matrix Operations in Matlab Dot product Cross product – Plotting.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
1. Exam Topics Difference between computers and calculators John creates a new device. It will compute the orbit of all the planets in the solar system.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Part 1 Chapter 3 Programming with MATLAB PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University.
Introduction to MATLAB. CSPP58001 MATLAB MATLAB is is a matrix-based language well suited for carrying out numerical analysis. It has many, many high-
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
CSE123 Lecture 3 Files and File ManagementScripts.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 7 : M-file Programming I Edward Cheung Room W311g 2008.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
전자장 1 실험 - Matlab 사용법 - Photonic Systems Laboratory School of EE, Seoul National University Photonic Systems Lab School of EECS, S.N.U.
1 Introduction to Matlab. 2 What is Matlab? Matlab is basically a high level language which has many specialized toolboxes for making things easier for.
Introduction to Matlab PHY September Why Matlab? No need to compile code Huge amount of built-in functions Highly optimized and fast, in general.
EEE 161 Applied Electromagnetics
Scripts & Functions Scripts and functions are contained in .m-files
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Programming The ideal style of programming is Structured or
Presentation transcript:

MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland

Sources James E. Gentle, 2002, Elements of Computational Statistics, Springer.

Topics Operators and Flow Control M-Files Functions Input and Output M-File Style Optimization Tutorial Individual Project

Operators and Flow Control Relational and Logical Operators Flow Control

Relational Operators The six relational operators are: –== (equal) –^= (not equal) –< –> –<= –>= True is 1 and false is 0 Comparisons involving matrices produce matrices.

Logical Functions ischar isempty isequal isfinite isieee isinf islogical isnan isnumeric isreal issparse

Logical Operators & (logical and) | (logical or) ~ (logical not) xor (logical exclusive or) all (true if all elements of vector are nonzero) any (true if any element of vector is nonzero)

Find The find() command returns the indices corresponding to the non-zero elements of a vector. Applied to a matrix M, it works with M(:). This can be used with any of these functions and operators. If f was generated by f = find(X), then X(f) are the non-zero elements of X.

If Then Else if expression (handled like C/C++/Java) statements (comma separated on one line) elseif expression2 (optional) elseif statements else (optional) final set of statements end

For Loop Convenient (but avoid if performance- critical; use vectors instead) for variable = expression for statements (, sep if 1 line) end Expression is usually i:s:j. It can be a matrix, in which case the columns from first to last are used.

While Loop while expression statements end As long as expression remains true (^==0) for and while loops can be terminated with a break. continue jumps back to the loop start. Infinite loop: while 1, …, end

Switch Statement switch expression case value1 statements case value2 statements case value3 statements otherwise statements (optional) end The case value can be a value list within {…} forming a cell array. This is different from C!!!!!

M-Files Scripts—no input or output arguments and operate on variables in the workspace Functions—contain a function definition line and can work with input and output arguments. Internal variables are local unless declared global.

Scripts Format for a script called spin.m: %SPIN % describes what it does executable statements

Functions function retval = name(arguments) %NAMEone line description. (H1 line) % more details including arguments code statements, eventually setting retval The name of the m-file should be the name of the function. The H1 line should omit ‘the’ and ‘a’. It should start with a capital letter and end with ‘.’. There is usually a blank line after the header. The return command can be used to exit.

Editing M-Files M-files are ASCII files, so you can use any text editor. MATLAB has a built-in editor/debugger. –Type edit –Or use the menu in Windows systems. MATLAB maintains a search path to find M-files. Use the path and addpath commands. There is also a path browser that can be called by pathtool. Relevant commands available include what, lookfor, help, type, exist, and more.

Function Details Functions can be passed as argument to other functions. Such an argument is preceded Handle it using feval. Functions can also be passed as name strings. This is not preferred. The vectorize() function can be used to convert multiplication, division, and exponentiation to array operations

Subfunctions Any M-file can contain local functions after the first one that can be called by the first one or other subfunctions. Usually you head a subfunction with % Subfunction Subfunctions can be arguments. Functions and subfunctions can call themselves recursively.

Input and Output User input Screen display Reading and writing text files

User Input The input function will display a prompt and wait for user input. Input is interpreted as a string if input is called with a second argument ‘s’. The function ginput collects data via mouse click coordinates. The function pause() suspends execution until a key is clicked. pause(n) waits n seconds.

Screen Display If you don’t append a ‘;’ there will be output to the screen. The disp(var) function displays var. The fprintf function gives more sophisticated control. The sprintf function returns a string that fprintf would have printed.

Text Files Type help iofun for the list of functions that support text and binary file io. These are generally similar to C functions.

M-File Style Be careful to fully document your files. In particular, provide an example of how the function can be used that can be cut and pasted. Space around logical operators and = One statement per line Indentation to emphasize structure. Matrix names should be capitalized.

Optimization You may compile M-files. Vectorize, don’t shade your eyes: n = 5e5; x = randn(n,1); tic, s = 0; for i=1:n, s = s+x(i)^2; end, toc Elapsed time = 8.35 tic, s = sum(x.^2); toc Elapsed time = 0.06

More Optimization Preallocate large arrays. Otherwise they may be expanded one row/column at a time. The repmat function is much faster than anything that involves manipulating individual matrix entries. Empty arrays/matrices are handled by extrapolating operations on non-empty ones. This may be very convenient.

Grand Tour Tutorial When a cluster of data points is rotated, patterns in the data may become apparent. Rotations are orthogonal transformations that preserve the norms of the data vectors and the angles between. Simple rotation matrices start with the identity matrix and change the four elements a ii, a ij, a ji, and a jj. a ii and a jj are replaced with cos(  ), a ij becomes sin(  ), and a ji becomes -sin(  ).

Generalized Rotation Matrices A generalized rotation matrix, Q, is the product of (d 2 -d)/2 such simple rotation matrices. Q = Q 12 Q 13 … Q 1d Q 23 Q 24 … Q 2d … Q d-1,d

Constructing the Plot Rotating a plot in all directions, and projecting into the first two or three dimensions is called a “Grand Tour” (Asimov 1985). You can take for the values of  ij, t  ij modulo 2  where the  ij are linearly independent over the integers. Suitable constants are the square roots of the first (d 2 -d)/2 primes. Plot the first two (or three) dimensions. Suitable data can be found here: Step time and observe the changes.

Suitable Data Can Be Found At: