Mikael Johansson and Frank Lingelbach Department of Signals, Sensors, and Systems Introduction to Matlab 2E1215, Lecture 2 – Matlab Programming

Slides:



Advertisements
Similar presentations
Introduction to Matlab
Advertisements

2.1 Program Construction In Java
Lecture 14 User-defined functions Function: concept, syntax, and examples © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
CIS 101: Computer Programming and Problem Solving Lecture 8 Usman Roshan Department of Computer Science NJIT.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Ordinary Differential Equations. Outline Announcements: –Homework II: Solutions on web –Homework III: due Wed. by 5, by Structs Differential Equations.
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
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.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/29/2003.
Advanced MATLAB (for Electrical Engineers) Instructor: Kamran Arshad EE Club, KFUPM 28 March 2004 KFUPM.
MATLAB Programming fprintf Cell arrays Structures Flow of control Vectorization Functions 1.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
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.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions.
CMPSC 200 Spring 2013 Lecture 38 November 18 or 20, 2013 (depending on section)
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
1 Tips for solving Project 1 Reactor SO 3 SO 2 +O 2.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
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.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
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)
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Algorithm Design.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
SIMULINK-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat.
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.
Matlab Programming for Engineers
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Matlab Programming a logical approach. Outline Announcements: –Homework I: due Wed. by 5, by –Last day to add/drop or change credit/audit Iteration.
Introduction to Matlab By: Jafar Muhammadi April 2005.
1 Lecture 4 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Recap Functions with No input OR No output Determining The Number of Input and Output Arguments Local Variables Global Variables Creating ToolBox of Functions.
General Computer Science for Engineers CISC 106 Lecture 15 Dr. John Cavazos Computer and Information Sciences 03/16/2009.
EGR 115 Introduction to Computing for Engineers Loops and Vectorization – Part 1 Monday 13 Oct 2014 EGR 115 Introduction to Computing for Engineers.
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.
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.
Review Expressions and operators Iteration – while-loop – for-loop.
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.
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.
1 Introduction to Engineering Spring 2007 Lecture 18: Digital Tools 2.
Introduction to Matlab
Matlab Training Session 4: Control, Flow and Functions
MatLab Programming By Kishan Kathiriya.
Think What will be the output?
Scripts & Functions Scripts and functions are contained in .m-files
Today’s Lecture Matlab programming
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.
Introduction to Matlab
REPETITION Why Repetition?
Presentation transcript:

Mikael Johansson and Frank Lingelbach Department of Signals, Sensors, and Systems Introduction to Matlab 2E1215, Lecture 2 – Matlab Programming ORG URL:

2 Programming in Matlab Script files Script-files contain a sequence of Matlab commands %FACTSCRIPT – Compute n-factorial, n!=1*2*...*n y = prod(1:n); %FACTSCRIPT – Compute n-factorial, n!=1*2*...*n y = prod(1:n); factscript.m  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!

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

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

5 Programming in Matlab 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 Exam: all problems will require you to write functions % FACTTEST – Test factfun N=50; y=factfun(N); % FACTTEST – Test factfun N=50; y=factfun(N); facttest.m

6 Programming in Matlab Flow control - selection The if-elseif-else construction if elseif else end if height>170 disp(’tall’) elseif height<150 disp(’small’) else disp(’average’) end if height>170 disp(’tall’) elseif height<150 disp(’small’) else disp(’average’) end

7 Programming in Matlab Logical expressions Relational operators (compare arrays of same sizes) ==(equal to)~= (not equal) (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 if (x>=0) & (x<=10) disp(‘x is in range [0,10]’) else disp(‘x is out of range’) end

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

9 Programming in Matlab Example – selection and repetition 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; end 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; end fact.m

10 Programming in Matlab Repetition: Animation demo The function movie replays a sequence of captured frames Construct a movie of a 360° tour around the Matlab logo % 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 % now display captured movie movie(gcf,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 % now display captured movie movie(gcf,M); logomovie.m

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

12 Programming in Matlab 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

13 Programming in Matlab Flow control – conditional repetition 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 end 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 end newton.m >> [x,n]=newton(0,1e-3,10)

14 Programming in Matlab Function functions 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); 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 [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); myfun.m

15 Programming in Matlab Function functions Can update newton.m >> [x,n]=newtonf(’myfun’,0,1e-3,10) 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 [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 newtonf.m

16 Programming in Matlab Function functions in Matlab Heavily used: integration, differentiation, optimization, … >> help ode45 Find the solution to the ordinary differential equation 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); 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); myodefun.m >> ode45(‘myodefun’,[0 10],[1;-10]);

17 Programming in Matlab Programming tips and tricks Programming style has huge influence on program speed! 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 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 tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; slow.m fast.m Loops are slow: Replace loops by vector operations! Memory allocation takes a lot of time: Pre-allocate memory! Use profile to find code bottlenecks!

18 Programming in Matlab 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  Have inputs, generate outputs, use internal variables  Flow control: ”if...elseif...if”, ”for”, ”while”  General-purpose functions: use functions as inputs Programming style and speed  Vectorization, memory allocation, profiler

19 Programming in Matlab Advanced Matlab Programming Functions  Can have variable number of inputs and outputs (see: nargin, nargout, varargin, varargout)  Can have internal functions (see page 53) Data types: more than just arrays and strings:  Structures (see page 67)  Cell arrays (see page 64) File handling  Supports most C-commands for file I/O (fprintf,…)

20 Programming in Matlab Advanced Matlab Programming Object-orientation (see pages 72-75)  Object: “structure” + methods  Creation, encapsulation, inheritage, aggregation Graphical user interfaces (see pages 76-83)  Based on “handle” concept for graphics (last lecture)  Menus, buttons, slides, and interactive graphics Interfacing other codes  Can call compiled C/C++ (“mex”), Java and ActiveX