MATLAB.

Slides:



Advertisements
Similar presentations
Introduction to Matlab
Advertisements

Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to MATLAB Simon O’Keefe Non-Standard Computation Group
Introduction to MATLAB Week 13 – 4/21/09. Instructor: Kate Musgrave Time: Tuesdays 3-5pm Office Hours: Tuesdays 1:30-3pm
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Exam #3 Review: Comprehensive Exam Class 14.2 Palm Matlab Book Ch. 1-5.
MATLAB Week 3 17 November Outline Graphics – Basic plotting – Editing plots from GUI – Editing plots from m-file – Advanced plotting commands.
MATLAB TUTORIAL Dmitry Drutskoy Some material borrowed from the departmental MATLAB info session by Philippe Rigollet Kevin Wayne.
Dr. Jie Zou PHY Welcome to PHY 3320 Computational Methods in Physics and Engineering.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
MATLAB Fundamentals.
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 INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Introduction to MATLAB
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to MATLAB CBE 502 Mathematical Methods of Engineering Analysis.
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.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Eng Ship Structures 1 Introduction to Matlab.
INTRODUCTION TO MATLAB LAB# 01
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Matlab The language of Technical computing Mr. D. Suresh Assistant Professor, Dept. of CSE, PSNA CET, Dindigul.
Lecture 2 - Matlab Introduction CVEN 302 June 5, 2002.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Master in Optical Fiber Communications and Photonic Technologies Foundations of Digital Transmission - Fall quarter Introduction to Matlab.
1 DKT 211 Basic Communication Engineering LAB # 1A : (Lecture 1) Introduction to Matlab  Basic Features  Scientific features  Array Operations  Script.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Introduction to Matlab By E. Noura Semary. Contents MATLAB Environment  Command window, Workspace, Path window, Editor window,and Figure window) Basic.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
EGR 106 Lecture 6 2-D Plotting Graphical presentation has become the standard method to show technical information. Engineers use plots to analyze, visualize,
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.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
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.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Introduction to Matlab Engr. Mian Shahzad Iqbal LAB NO.2
CS100A, Fall 1998, Lecture 191 CS100A, Fall 1998 Lecture 19, Thursday Nov 05 Matlab Concepts: Matlab arrays Matlab subscripting Matlab plotting.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
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.
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators.
Computer Application in Engineering Design
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
MATLAB DENC 2533 ECADD LAB 9.
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files)
Introduction to MATLAB Plotting LAB 3
INTRODUCTION TO MATLAB
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Presentation transcript:

MATLAB

Generating Vectors from functions zeros(M,N) MxN matrix of zeros ones(M,N) MxN matrix of ones rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1) x = zeros(1,3) x = 0 0 0 x = ones(1,3) 1 1 1 x = rand(1,3) 0.9501 0.2311 0.6068

Numeric Arrays Two-dimensional arrays, called a matrix in MATLAB often Size = rows by columns [r c] = size(array_name) if array_name is a matrix size will work for n-dimension arrays and output size of each dimension into a row vector Basic matrix creation: 3

Numeric Arrays How do you multiply to arrays element-by-element? Do it in a for loop Very slow, avoid whenever possible Use element-by-element operations Addition and subtraction are the same: +, - Multiplication, right and left division and exponentiation use “.” before the symbol i.e. foo.*bar or foo./bar or foo.^3 4

Numeric Arrays Examples of element-by-element operation results 5

Numeric Arrays Matrix operations Matrix operations are the same symbols as standard scalar operations Apply when multiplying or dividing matrices 6

Numeric Arrays Useful built-in functions for working with arrays Size, linspace and logspace were already mentioned Num_of_elements = length(array) Returns the length of the longest dimension Max_val = max(array) Returns the largest element in the array if it is a vector Returns a row vector of the largest element if the array is a matrix min_val = min(array) Same as max, but returns the minimum values 7

Numeric Arrays sum(array) find(array) Returns the sum of a vector or a row vector of the sum of each column find(array) Returns an array with the locations of the nonzero elements of the array 8

Numeric Arrays When dealing with numeric arrays, the clear function can come in handy If you have foo declared as a 2x2 array Then create two 5x1 arrays, x and y Try to do: foo(:,1) = x Produces an error because MATLAB thinks foo should be a 2x2 array and x won’t fit into the first column of foo Use clear to reset foo 9

Numeric Arrays MATLAB can create several special matrices Identity, zeros and ones Useful for initializing matrices to ones, zeros or when you may need to use the identity matrix MATLAB also has functions to check for NaN, inf, or if an array is empty isnan, isempty, isinf 10

Cell Arrays A cell array is an array where each element can contain another array with different dimensions if needed Cell arrays can hold different classes of arrays Cell arrays aren’t used too much in most MATLAB sessions I’ve only used them for one type of FILE I/O They are used in some toolboxes too 11

Cell Arrays Creating a cell array is very similar to creating a numerical array To create a cell array, use {} instead of [] Cell arrays can also be created one element at a time or pre-allocated and then defined 12

Cell Arrays Indexing a cell array is more complex than a numeric array To display a list of each cell and the type of array in each cell: A(:) cellplot(A) will give a graphical representation of the cell array To display the contents of each cell: A{:} To go into an array in a given cell location use a combination of () and {} A{1}(2,2) will return the element at (2,2) for the array in the first cell of A 13

Structures Structures are a MATLAB data type used to store different types of data in a single unit A structure consists of fields Each field contains an array of some MATLAB type Actually similar to a cell array in that it combines different sized arrays of various data types into one entity 14

Structures Two ways to create a structure in MATLAB Define each field of a structure individually Structure_name.field_name Use the struct function call 15

Structures One more example 16

Structure Arrays MATLAB can create arrays of structures Just add in the index of the array location before the field name Can create n-dimension structure arrays 17

Structure Arrays Indexing structures and structure arrays can get complicated You need to specify location in structure array, field name and field location Structures can contain cell arrays, further complicating things Nested structures are possible too 18

Structure Arrays Some simple examples See MATLAB help for much more in-depth discussion on structures or cell arrays for that matter 19

Strings Strings are just character arrays Can be multidimensional However, then each string is required to be the same length to keep array rectangular Cell arrays are handy for multiple strings of different length File I/O of characters (discussed later today) 20

Strings Examples We’ve already seen many examples scattered throughout the first two lectures, but here a few more 21

Strings Useful functions String manipulation: sprintf, strcat, strvcat, sort, upper, lower, strjust, strrep, strtok, deblank, etc. String comparisons Should use strcmp when comparing strings If you have two strings A and B, A==B will give a row vector of results for each character Strcmp will compare the entire string, or a subset if you want 22

M-Files M-files are essentially script files where you can place a bunch of MATLAB commands and execute the m-file repeatedly Can have everything in an m-file, function calls, variable allocation, function definitions, figure generation and modification, etc Nearly everything will probably be done in an m-file, rather than at the command prompt 23

M-Files MATLAB has the editor window for creating, editing, debugging, running and saving m-files MATLAB color codes m-files for easier reading There is also real-time syntax checking Essentially spell check for code 24

Use of M-File Extension “.m” Click to create a new M-File Extension “.m” A text file containing script or function or program to run

Use of M-File Save file as Denem430.m If you include “;” at the end of each statement, result will not be shown immediately

Command line Make sure current path (pwd) cd to your m-file directory edit m1.m type m1.m To run the m1 (>>m1)

Flow Control if for while break ….

Programming with Matlab Relational operators < less than <= less than or equal to > greater than >= greater than or equal to = = equal to ~= not equal to Logical operations ~ not & and | or xor(a,b) exclusive or

Control Structures If Statement Syntax if (Condition_1) Some Dummy Examples if ((a>3) & (b==5)) Some Matlab Commands; end if (a<3) elseif (b~=5) else If Statement Syntax if (Condition_1) Matlab Commands elseif (Condition_2) elseif (Condition_3) else end

Control Structures For loop syntax for i=Index_Array Matlab Commands Some Dummy Examples for i=1:100 Some Matlab Commands; end for j=1:3:200 for m=13:-0.2:-21 for k=[0.1 0.3 -13 12 7 -9.3] For loop syntax for i=Index_Array Matlab Commands end

Control Structures While Loop Syntax while (condition) Matlab Commands end Dummy Example while ((a>3) & (b==5)) Some Matlab Commands; end

switch expression case value(1) statement(1) case value(2) statement(2) … case value(n-1) statement(n-1) otherwise statement(n) end

m2.m y = [3 4 5 9 2]; for i = 1:length(y) if rem(y(i),3)==0 fprintf('y(%g)=%g is 3n.\n', i, y(i)); elseif rem(y(i), 3)==1 fprintf('y(%g)=%g is 3n+1.\n', i , y(i)); else fprintf('y(%g)=%g is 3n+2.\n', i , y(i)); end

m3.m for i = 1:1000 if prod(1:i) > 1e100 fprintf('%g! = %e > 1e100\n', i, prod(1:i)); break; end

m4.m for month = 1:12 switch month case {3,4,5} season = 'Spring'; season = 'Summer'; case {9,10,11} season = 'Autumn'; case {12,1,2} season = 'Winter'; end fprintf('Month %d ===> %s.\n', month, season);

Function A function file is useful when you need to repeat a set of commands several times. function [output variables] = function_name(input variables); All the variables in a function file are local, (i) output variables are enclosed in square brackets, the square brackets are optional when there is only one output. (ii) input variables are enclosed with parentheses (iii) function_name must be the same as the filename in which it is saved (with the .m extension) (iv) function is called by its name

Myfun.m myfun(2,3) % called with zero outputs function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; myfun(2,3) % called with zero outputs u = myfun(2,3) % called with one output [u v w] = myfun(2,3) % called with all outputs

func3.m [a, b] = func3([1 2 3], [4 5 6 7 8]) function [ave1, ave2] = func3(vector1, vector2); ave1 = sum(vector1)/length(vector1); ave2 = sum(vector2)/length(vector2); [a, b] = func3([1 2 3], [4 5 6 7 8])

func4.m [a, b] = func4([1 2 3], [4 5 6 7 8]) c = func4([1 3 5 7 9]) function [ave1, ave2] = func4(vector1, vector2) if nargin == 1 % only one variable ave1 = sum(vector1)/length(vector1); end if nargout == 2 % two variables ave2 = sum(vector2)/length(vector2); [a, b] = func4([1 2 3], [4 5 6 7 8]) c = func4([1 3 5 7 9]) bar(sin(func4([1 3 5 7 9])))

Elementary Math Function Abs(), sign() Sign(A) = A./abs(A) Sin(), cos(), asin(), acos() Exp(), log(), log10() Ceil(), floor() Sqrt() Real(), imag() 41

I/O fid = fopen(‘1.txt','r'); i = 1; while ~feof(fid) name(i,:) = fscanf(fid,'%5c',1); year(i) = fscanf(fid,'%d',1); no1(i) = fscanf(fid,'%d',1); no2(i)=fscanf(fid,'%d',1); no3(i)=fscanf(fid,'%g',1); no4(i)=fscanf(fid,'%g\n'); i=i+1; year end fclose(fid);

Alt. name{i} = fscanf(fid, ‘%s’, 1);

1.txt John 1995 12 5 2.3 4.5 Mary 1975 2 12 4.5 5.3

time tic % start inv(rand(500)); % Matrix inverse. toc

t0 = cputime; % time now a = inv(rand(500)); % cpuTime = cputime-t0 % cpu time I/O time are ingored

Time for every command profile on -detail mmex for i = 1:1000 a = inv(rand(100)); b = mean(rand(100)); end profile off profile report

Basic Plotting plot(x,y) figure(n) Basic MATLAB plotting command Creates figure window if not already created Autoscales each axis to fit data range Can add axes object properties after x,y figure(n) Will create a new figure window MATLAB will use current figure window by default Plot command will overwrite figure if called repeatedly given same current figure window 48

Basic Task: Plot the function sin(x) between 0≤x≤4π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Plot the y-array >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y)

Plot the function e-x/3sin(x) between 0≤x≤4π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Calculate e-x/3 of the x-array >>x=linspace(0,4*pi,100); >>y=sin(x); >>y1=exp(-x/3);

Plot the function e-x/3sin(x) between 0≤x≤4π Multiply the arrays y and y1 correctly Plot the y2-array >>y2=y.*y1; >>plot(y2)

Practice plot(x,sin(x), x, cos(x), x, sin(x)+cos(x)); Figure(2); plot(x, sin(x), 'o', x, cos(x), 'x', x, sin(x)+cos(x), '*'); plot(x, y,'k:diamond') grid on

plot color Plot-color color RGB b (Blue) (0,0,1) c (Cyan) (0,1,1) g (Green) (0,1,0) k (Black) (0,0,0) m (Magenta) (1,0,1) r (Red) (1,0,0) w (White) (1,1,1) y (Yellow) (1,1,0)

Modifying Plots Line markers Can choose to add markers at each data point Can have only markers, no line 54

Modifying Plots Line width Line style Specified by an integer, default is 0.5 points Each point is 1/72 of an inch Line style 55

x = peaks %generate a 49*49 matrix y = x'; plot(x, y);

Display Facilities title(.) xlabel(.) ylabel(.) >>title(‘This is the sinus function’) >>xlabel(‘x (secs)’) >>ylabel(‘sin(x)’)

Subplots h = subplot(m,n,p) or subplot(mnp) h = subplot(m,n,p,'replace') Three typical syntax uses for subplot command Subplot will generate m by n subplots on a figure object p specifies which subplot to create out of the m*n total ‘replace’ will overwrite any subplot in that current position 58

Subplots 59

Subplots 60

x = 0:0.1:4*pi; subplot(2, 2, 1); plot(x, sin(x)); subplot(2, 2, 2); plot(x, cos(x)); subplot(2, 2, 3); plot(x, sin(x).*exp(-x/5)); subplot(2, 2, 4); plot(x, x.^2);

Bar Graphs MATLAB will plot horizontal and vertical bar graphs 62

Modifying Plots set(h,'PropertyName',PropertyValue,...) The set command takes object handle h and sets property values for give property names for that object handle If h is an array, the property values will be set for all object handles in h a = get(h,'PropertyName') get returns the value of a given property 63

Modifying Plots gcf stands for get current figure handle Will return handle of current figure gca stands for get current axis handle Will return handle of current axis These two commands are very useful when used in conjunction with the set and get commands Allows you to edit the properties of the current figure or axis without having the handle specified in a variable 64

x = 0:0.1:4*pi; plot(x, sin(x)+sin(3*x)) set(gca, 'ytick', [-1 -0.3 0.1 1]); set(gca, 'yticklabel', {'min.', 'point 1', 'point 2', 'max. '}); grid on