Introduction to Matlab By: Jafar Muhammadi April 2005.

Slides:



Advertisements
Similar presentations
Introduction to Matlab
Advertisements

Introduction to MATLAB
Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
MATLAB Basics CS 111 Introduction to Computing in Engineering and Science.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Advanced MATLAB (for Electrical Engineers) Instructor: Kamran Arshad EE Club, KFUPM 28 March 2004 KFUPM.
Introduction to 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.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
WELCOME EF 105 Fall 2006 Week 10. Topics: 1. Engineering Problem Solving 2.Programming Logic 3.Intro to MATLAB.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
Introduction to MATLAB ENGR 1181 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Mikael Johansson and Frank Lingelbach Department of Signals, Sensors, and Systems Introduction to Matlab 2E1215, Lecture 2 – Matlab Programming
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
MATLAB Practice 1 Introducing MATLAB Lecture Notes on Video Search & Mining, Spring 2012 Presented by Jun Hee Yoo Biointelligence Laboratory School of.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
CMPS 1371 Introduction to Computing for Engineers MatLab.
10/24/20151 Chapter 2 Review: MATLAB Environment 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)
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Introduction to Matlab By E. Noura Semary. Contents MATLAB Environment  Command window, Workspace, Path window, Editor window,and Figure window) Basic.
MATLAB Lecture Two Tuesday 5 July Chapter 3.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
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.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
The Hong Kong Polytechnic University Industrial Centre MatLAB Lesson 1 : Overview & Environment Edward Cheung Room W311g.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
MATLAB Lecture 1 염익준. Introduction MATLAB (MATrix LABoratory) a special purpose computer program optimized to perform engineering and scientific calculations.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
MATLAB Constants, Variables & Expression Nafees Ahmed Asstt. Professor, EE Deptt DIT, DehraDun.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Matlab Tutorial Iman Moazzen First Session – September 11, 2013.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
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.
Introduction to Matlab
Matlab Programming for Engineers
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
Today’s Lecture Matlab programming
StatLab Matlab Workshop
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
MATLAB Basics.
Lecture 2 Introduction to MATLAB
Experiment No. (1) - an introduction to MATLAB
Introduction to Matlab
CS 111 Introduction to Computing in Engineering and Science
Matlab Basics.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

Introduction to Matlab By: Jafar Muhammadi April 2005

MATrix LABoratory   Advantages of MATLAB  Ease of use  Platform independence  Predefined functions  Plotting  Disadvantages of MATLAB  Can be slow  Expensive

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) Core m-files C-kernel Sig. Proc Contr. Syst. User defined

Matlab Desktop Command Window Launch Pad History

Matlab Desktop Command Window Workspace Current DIrectory

Matlab Help

Matlab Editor Color keyed text with auto indents tabbed sheets for other files being edited

MATLAB Basics  A program can be input  command by command using the command line (lines starting with “»” on the MATLAB desktop)  as a series of commands using a file (a special file called M-file)  If a command is followed by a semicolon (;), result of the computation is not shown on the command window

Data Types  All numbers are double precision  Text is stored as arrays of characters  You don’t have to declare the type of data (defined when running)  MATLAB is case-sensitive!!!

Data Types

Variables  Variable is a name given to a reserved location in memory  class_code = 111;  number_of_students = 65;  name = ‘Jafar Muhammadi';  radius = 5;  area = pi * radius^2;  Use meaningful names for variables  MATLAB variable names  must begin with a letter  can contain any combination of letters, numbers and underscore (_)  must be unique in the first 31 characters  MATLAB is case sensitive: “name”, “Name” and “NAME” are considered different variables  Never use a variable with the same name as a MATLAB command  Naming convention: use lowercase letters

Variables  Initialization using assignment statements  x = 5 x = 5  y = x + 1 y = 6  vector = [ ] vector =  matrix = [ 1 2 3; ] matrix =  matrix = [ 1 2 3; 4 5 ] ??? Error  a = [ 5 (2+4) ] a = 5 6

Variables  Initialization using shortcut statements  colon operator  first:increment:last  x = 1:2:10 x =  y = 0:0.1:0.5 y =

Variables  transpose operator  '  u = [ 1:3 ]' u =  v = [ u u ] v =  v = [ u'; u' ] v =

Variables  Initialization using built-in functions  zeros()  x = zeros(2) x =  z = zeros(2,3) z =  ones(), size(), length()  y = zeros(1,4) y =  t = zeros( size(z) ) t =

Matrices  Some useful commands: zeros(n)Returns a n X n matrix of zeros zeros(m,n)Returns a m X n matrix of zeros ones(n)Returns a n X n matrix of ones ones(m,n)Returns a m X n matrix of ones size(A) For a m X n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix length(A)Returns the larger of the number of rows or columns in A

Variables  Initialization using keyboard input  input()  value = input( 'Enter an input value: ' ) Enter an input value: 1.25 value =  name = input( 'What is your name: ', 's' ) What is your name: Selim name = Selim

Matrices, Colon Operator  Creating new matrices from an existing matrix C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4] F = C(:, 2:3) = [2,5; 0,1; 2,-1; 1,4]

Matrices, Colon Operator  Creating new matrices from an existing matrix C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4] E = C(2:3,:) = [-1 0 1; ]

Matrices, Colon Operator  Creating new matrices from an existing matrix C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4] G = C(3:4,1:2) = [3,2; 0,1]

Matrices, Colon Operator  Variable_name = a:step:b time = 0.0:0.5:2.5 time = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]  Negative increment values = 10:-1:2 values = [10, 9, 8, 7, 6, 5, 4, 3, 2]

Subarrays  Array indices start from 1  x = [ ];  x(2) ans = 0  x(4) ans = 1  x(8) ??? Error  x(-1) ??? Error

Subarrays  y = [ 1 2 3; ];  y(1,2) ans = 2  y(2,1) ans = 4  y(2) ans = 4 (column major order)

Subarrays  y = [ 1 2 3; ];  y(1,:) ans =  y(:,2) ans = 2 5  y(2,1:2) ans = 4 5  y(1,2:end) ans = 2 3  y(:,2:end) ans =

Subarrays  x = [ ];  x(2) = 5 x =  x(4) = x(1) x =  x(8) = -1 x =

Subarrays  y = [ 1 2 3; ];  y(1,2) = -5 y =  y(2,1) = 0 y =  y(1,2:end) = [ -1 9 ] y =

Subarrays  y = [ 1 2 3; 4 5 6; ];  y(2:end,2:end) = 0 y =  y(2:end,2:end) = [ -1 5 ] ??? Error  y(2,[1 3]) = -2 y =

Special Values  pi:  value up to 15 significant digits  i, j: sqrt(-1)  Inf: infinity (such as division by 0)  NaN: Not-a-Number (such as division of zero by zero)  clock: current date and time as a vector  date: current date as a string (e.g. 16-Feb-2004)  eps: epsilon  ans: default variable for answers

Displaying Data  The disp( array ) function  disp( 'Hello' ); Hello  disp(5); 5  disp( [ 'Bilkent ' 'University' ] ); Bilkent University  name = 'Selim'; disp( [ 'Hello ' name ] ); Hello Selim

Displaying Data  The num2str() and int2str() functions  d = [ num2str(16) '-Feb-' num2str(2004) ];  disp(d); 16-Feb-2004  x = 23.11;  disp( [ 'answer = ' num2str(x) ] ); answer =  disp( [ 'answer = ' int2str(x) ] ); answer = 23

Displaying Data  The fprintf( format, data ) function  %dinteger  %ffloating point format  %eexponential format  \nnew line character  \ttab character

Displaying Data  fprintf( 'Result is %d', 3 ); Result is 3  fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 ); Area of a circle with radius 3 is  x = 5;  fprintf( 'x = %3d', x ); x = 5  x = pi;  fprintf( 'x = %0.2f', x ); x = 3.14  fprintf( 'x = %6.2f', x ); x = 3.14  fprintf( 'x = %d\ny = %d\n', 3, 13 ); x = 3 y = 13

Data Files  save filename var1 var2 …  save homework.mat x y  binary  save x.dat x –ascii  ascii  load filename  load filename.mat  binary  load x.dat –ascii  ascii

MATLAB Basics: Scalar Operations  variable_name = expression;  additiona + b  a + b  subtractiona - b  a - b  multiplicationa x b  a * b  divisiona / b  a / b  exponenta b  a ^ b

MATLAB Basics: Scalar Operations  x = 3 * / 2  x = ?  Processing order of operations is important  parenthesis (starting from the innermost)  exponentials (left to right)  multiplications and divisions (left to right)  additions and subtractions (left to right)  x = 3 * / 2  x = 9

Arithmetic Operators OperatorDescription + Addition - Subtraction.* Multiplication (element wise)./ Right division (element wise).\ Left division (element wise) + Unary plus - Unary minus : Colon operator.^ Power (element wise) ' Transpose * Matrix multiplication / Matrix right division \ Matrix left division ^ Matrix power

Relational and Logical Operators OperatorDescription & Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elements. | Returns 1 for every element location that is true (nonzero) in either one or the other, or both, arrays and 0 for all other elements. ~ Complements each element of input array, A. < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to

Matrices  More commands: Transpose B=A ’ Identity Matrix eye(n) -> returns an n X n identity matrix eye(m,n) -> returns an m X n matrix with ones on the main diagonal and zeros elsewhere Addition and SubtractionC =A +B C =A - B Scalar MultiplicationB = α A, where α is a scalar Matrix MultiplicationC = A * B Matrix InverseB = inv(A), A must be a square matrix in this case Matrix powersB = A * A, A must be a square matrix Determinantdet(A), A must be a square matrix

MATLAB Basics: Built-in Functions  result = function_name( input );  abs, sign  log, log10, log2  exp  sqrt  sin, cos, tan  asin, acos, atan  max, min  round, floor, ceil, fix  mod, rem  help elfun

MATLAB Basics: Useful Commands  help command  Online help  lookfor keyword  Lists related commands  which  Version and location info  clear  Clears the workspace  clc  Clears the command window  diary filename  Sends output to file  diary on/off  Turns diary on/off  who, whos  Lists content of the workspace  more on/off  Enables/disables paged output  Ctrl+c  Aborts operation  …  Continuation  %  Comments

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  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!

Functions  Functions describe subprograms  Take inputs, generate outputs  Have local variables (invisible in global workspace) [output_arguments]= function_name(input_arguments) % Comment lines 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);

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

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

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

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

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; 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; fact.m

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)]);

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!