Introduction to Matlab

Slides:



Advertisements
Similar presentations
M. Dumbser 1 / 23 Analisi Numerica Università degli Studi di Trento Dipartimento dIngegneria Civile ed Ambientale Dr.-Ing. Michael Dumbser Lecture on Numerical.
Advertisements

2.1 Program Construction In Java
Introduction To MATLAB Prof. Muhammad Saeed Mathematical Modeling and Simulation.
DIVIDING INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
Lecture 10 Flow of Control: Loops (Part 2) COMP1681 / SE15 Introduction to Programming.
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Lecture 7: Software Design (Part II)
Insight Through Computing 7. The While-Loop For-Loop Problems Introduce While-Loops.
CS101: Introduction to Computer programming
C-LISP. LISP 2 Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT).John McCarthyMassachusetts Institute.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 10 – Enhancing the Wage Calculator Application:
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Lecture 14 User-defined functions Function: concept, syntax, and examples © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Lecture 5.
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Lecture 4 Structure plan Program design process Program design process Basic elements of code: Basic elements of code: –Input (assignment of variables)
Lecture 14: Newton’s method for system of two nonlinear equations Function newton2d01 Set initial (x,y) point, maximum number of iterations, and convergence.
CS 111: Introduction to Programming Midterm Exam NAME _________________ UIN __________________ 10/30/08 1.Who is our hero? 2.Why is this person our hero?
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 7 Sept 29 Goals: Chapters 5 and 6. Scripts Sequence of instructions that we may want to run can be stored in a file (known as script). by typing.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
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.
Mikael Johansson and Frank Lingelbach Department of Signals, Sensors, and Systems Introduction to Matlab 2E1215, Lecture 2 – Matlab Programming
Linux Operations and Administration
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Lecture 7 Sept 22 Goals: Chapters 5 and 6. Scripts Sequence of instructions that we may want to run can be stored in a file (known as script). by typing.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
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)
Engr 0012 (04-1) LecNotes script/function comparison scriptsfunctions Show program logic answer “what” questions Show program details answer “how”
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
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.
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Introduction to Matlab By: Jafar Muhammadi April 2005.
How Are Computers Programmed? CPS120: Introduction to Computer Science Lecture 5.
Controlling Program Flow with Decision Structures.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Flowchart. a diagram of the sequence of movements or actions of people or things involved in a complex system or activity. a graphical representation.
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.
A L I MAM M OHAMMAD B IN S AUD I SLAMIC U NIVERSITY C OLLEGE OF S CIENCES D EPARTMENT OF M ATHEMATICS MATLAB 251 : MATH SOFTWARE Introduction to MATLAB.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Introduction to Matlab
Introduction to Matlab
Matlab Training Session 4: Control, Flow and Functions
Chapter 9 Recursion.
Topic: Functions – Part 2
Think What will be the output?
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB DENC 2533 ECADD LAB 9.
User Defined Functions
Today’s Lecture Matlab programming
Matlab review Matlab is a numerical analysis system
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Computer Science Core Concepts
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Matlab Basics.
REPETITION Why Repetition?
Programming The ideal style of programming is Structured or
Presentation transcript:

Introduction to Matlab 2E1215, Lecture 2 – Matlab Programming http://www.s3.kth.se/control/kurser/2E1215/ Based on lectures by F. Gustafsson, Linköping University

Today’s Lecture Matlab programming Programming environment and search path M-file scripts and functions Flow control statements Function functions Programming tricks and tips

Matlab environment Matlab construction Core functionality as compiled C-code, m-files Additional functionality in toolboxes (m-files) Today: Matlab programming (construct own m-files) Contr. Syst. Sig. Proc User defined Core m-files C-kernel

The programming environment The working directory is controlled by >> dir >> cd catalogue >> pwd The path variable defines where matlab searches for m-files >> path >> addpath >> pathtool >> which function

The programming environment Matlab can’t tell if identifier is variable or function >> z=theta; Matlab searches for identifier in the following order 1. variable in current workspace 2. built-in variable 3. built-in m-file 4. m-file in current directory 5. m-file on search path Note: m-files can be located in current directory, or in path

Script files factscript.m Script-files contain a sequence of Matlab commands factscript.m %FACTSCRIPT – Compute n-factorial, n!=1*2*...*n y = prod(1:n); Executed by typing its name >> factscript Operates on variables in global workspace Variable n must exist in workspace Variable y is created (or over-written) Use comment lines (starting with %) to document file!

Displaying code and getting help To list code, use type command >> type factscript The help command displays first consecutive comment lines >> help factscript

Functions factfun.m Functions describe subprograms Take inputs, generate outputs Have local variables (invisible in global workspace) [output_arguments]= function_name(input_arguments) % Comment lines <function body> factfun.m function [z]=factfun(n) % FACTFUN – Compute factorial % Z=FACTFUN(N) z = prod(1:n); >> y=factfun(10);

Scripts or function: when use what? Functions Take inputs, generate outputs, have internal variables Solve general problem for arbitrary parameters Scripts Operate on global workspace Document work, design experiment or test Solve a very specific problem once Often: run user-function for specific parameters facttest.m % FACTTEST – Test factfun N=50; y=factfun(N);

Flow control - selection The if-elseif-else construction if <logical expression> <commands> elseif <logical expression> else end if height>170 disp(’tall’) elseif height<150 disp(’small’) else disp(’average’) end

Logical expressions Relational operators (compare arrays of same sizes) == (equal to) ~= (not equal) < (less than) <= (less than or equal to) > (greater than) >= (greater than or equal to) Logical operators (combinations of relational operators) & (and) | (or) ~ (not) Logical functions xor isempty any all if (x>=0) & (x<=10) disp(‘x is in range [0,10]’) else disp(‘x is out of range’) end

Flow control - repetition Repeats a code segment a fixed number of times for index=<vector> <statements> end The <statements> are executed repeatedly. At each iteration, the variable index is assigned a new value from <vector>. for k=1:12 kfac=prod(1:k); disp([num2str(k),’ ‘,num2str(kfac)]) end

Example – selection and repetition fact.m function y=fact(n) % FACT – Display factorials of integers 1..n if nargin < 1 error(’No input argument assigned’) elseif n < 0 error(’Input must be non-negative’) elseif abs(n-round(n)) > eps error(’Input must be an integer’) end for k=1:n kfac=prod(1:k); disp([num2str(k),’ ’,num2str(kfac)]) y(k)=kfac; end;

Repetition: Animation demo The function movie replays a sequence of captured frames Construct a movie of a 360° tour around the Matlab logo logomovie.m % logomovie – make movie of 360 degree logo tour logo; no_frames=40; dtheta=360/no_frames; for frame = 1:no_frames, camorbit(dtheta,0) M(frame) = getframe(gcf); end

Animation demo >> movie(gcf,M)

Flow control – conditional repetition while-loops while <logical expression> <statements> end <statements> are executed repeatedly as long as the <logical expression> evaluates to true k=1; while prod(1:k)~=Inf, k=k+1; end disp([‘Largest factorial in Matlab:’,num2str(k)]);

Flow control – conditional repetition Solutions to nonlinear equations can be found using Newton’s method Task: write a function that finds a solution to Given , iterate maxit times or until

Flow control – conditional repetition newton.m function [x,n] = newton(x0,tol,maxit) % NEWTON – Newton’s method for solving equations % [x,n] = NEWTON(x0,tol,maxit) x = x0; n = 0; done=0; while ~done, n = n + 1; x_new = x - (exp(-x)-sin(x))/(-exp(-x)-cos(x)); done=(n>=maxit) | ( abs(x_new-x)<tol ); x=x_new; end >> [x,n]=newton(0,1e-3,10)

Function functions myfun.m Do we need to re-write newton.m for every new function? No! General purpose functions take other m-files as input. >> help feval >> [f,f_prime]=feval(’myfun’,0); myfun.m function [f,f_prime] = myfun(x) % MYFUN– Evaluate f(x) = exp(x)-sin(x) % and its first derivative % [f,f_prime] = myfun(x) f=exp(-x)-sin(x); f_prime=-exp(-x)-cos(x);

Function functions newtonf.m Can update newton.m >> [x,n]=newtonf(’myfun’,0,1e-3,10) newtonf.m function [x,n] = newtonf(fname,x0,tol,maxit) % NEWTON – Newton’s method for solving equations % [x,n] = NEWTON(fname,x0,tol,maxit) x = x0; n = 0; done=0; while ~done, n = n + 1; [f,f_prime]=feval(fname,x); x_new = x – f/f_prime; done=(n>maxit) | ( abs(x_new-x)<tol ); x=x_new; end

Function functions in Matlab Heavily used: integration, differentiation, optimization, … >> help ode45 Find the solution to the ordinary differential equation myodefun.m function x_dot = myodefun(t,x) % MYODEFUN – Define RHS of ODE x_dot(1,1)=x(2); x_dot(2,1)=-x(1)+0.1*(1-x(1)^2)*x(2); >> ode45(‘myodefun’,[0 10],[1;-10]);

Programming tips and tricks Programming style has huge influence on program speed! slow.m tic; X=-250:0.1:250; for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end; toc fast.m tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; Loops are slow: Replace loops by vector operations! Memory allocation takes a lot of time: Pre-allocate memory! Use profile to find code bottlenecks!

Summary User-defined functionality in m-files Stored in current directory, or on search path Script-files vs. functions Functions have local variables, Scripts operate on global workspace Writing m-files Header (function definition), comments, program body Flow control: ”if...elseif...if”, ”for”, ”while” General-purpose functions: use functions as inputs Programming style and speed Vectorization, memory allocation, profiler