What is MATLAB ? MATrix LABoratory Developed by The Mathworks, Inc (http://www.mathworks.com(The Mathworks, Inc Interactive, integrated, environment –for.

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

Lecture 5.
Introduction to MATLAB The language of Technical Computing.
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Introduction to Graphing Using MATLAB. Line Graphs  Useful for graphing functions  Useful for displaying data trends over time  Useful for showing.
Introduction to M ATLAB Programming
Scripts and Flow Control. Scripts So far we have been entering commands directly into the command line But there is a better way Script files (and functions)
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to MATLAB
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter 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.
Matlab intro The Environment
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
MATLAB Fundamentals.
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.
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
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
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.
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.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
INTRODUCTION TO MATLAB LAB# 01
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.
MATLAB Harri Saarnisaari, Part of Simulations and Tools for Telecommunication Course.
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Introduction to MATLAB. CSPP58001 MATLAB MATLAB is is a matrix-based language well suited for carrying out numerical analysis. It has many, many high-
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
OUTLINE Overview Numbers, variables and similar in Matlab
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB Lecture 18.
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
INTRODUCTION TO MATLAB MATLAB is a software package for computation in engineering, science, and applied mathemat-ics. It offers a powerful programming.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
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.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
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 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.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
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
Matlab Training Session 4: Control, Flow and Functions
MATLAB DENC 2533 ECADD LAB 9.
StatLab Matlab Workshop
Use of Mathematics using Technology (Maltlab)
Lecture 2 Introduction to MATLAB
INTRODUCTION TO MATLAB
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
How to Use MATLAB A Brief Introduction.
Presentation transcript:

What is MATLAB ? MATrix LABoratory Developed by The Mathworks, Inc ( Mathworks, Inc Interactive, integrated, environment –for numerical computations –for symbolic computations –for scientific visualizations It is a high-level programming language

Characteristics of MATLAB Programming language based (principally) on matrices. –Slow - an interpreted language, i.e. not pre-compiled. Avoid for loops; instead use vector form whenever possible. –Automatic memory management, i.e., you don't have to declare arrays in advance. –Intuitive, easy to use. –Shorter program development time than traditional programming languages such as Fortran and C. –Can be converted into C code via MATLAB compiler for better efficiency. Many application-specific toolboxes available.

Start menu Matlab MATLAB “>>” – שורת הפקודה << date

Getting Help << help date >> helpwin date helpwin gives you the same information as help, but in a different window.

Getting Help << doc date << lookfor date % search for keywords that best describe the function >> Ctrl+C % stop Matlab from running >> clc % clear screen

Special characters >> % default command prompt % % comment - MATLAB simply ignores anything to the right of this sign (till the end of the line). >> % my comment ; % semicolon at the end of the line will prevent MATLAB from echoing the information you type on the screen. >> a=20 >> B=20;

Creating Variables Matlab as a calculator: >>2+5 >>7*10+8 >>5^2 ‘ans’ - "answer", used in MATLAB as the default variable.

Defining Your Own Variables When Matlab comes across a new variable name - it automatically creates it. Begins with a LETTER, e.g., A2z. Can be a mix of letters, digits, and underscores (e.g., vector_A, but not vector-A) Not longer than 31 characters. No spaces Different mixes of capital and small letters = different variables. For example: "A_VaRIAbLe", "a_variable", "A_VARIABLE", and "A_variablE >> String=‘this is a string’

Listing & Clearing Variables << whos << clear, clear all %clear variables from memory << a=10 << b = 20 << the_average = (a + b ) / 2

Creating vectors Row separator: space/coma (,) Creating sequences: From : jump: till linespec(X1, X2, N) generates N points between X1 and X2. Coulmn separator: Semicolon (;)

Creating Matrices Matrices must be rectangular. Creating random matrices: 2-by-4 random matrix (2 rows and 4 columns).

Creating Matrices You can combine existing vectors as matrix elements: You can combine existing matrices as matrix elements:

Indexing Into a Matrix >> B=A(3,1); >> A(:,end)=[1;7;3;8;4]; The row number is first, followed by the column number.

Linear Algebra Operations

Matrix Multiplication Inner dimensions must be equal Dimension of resulting matrix = outermost dimensions of multiplied matrices Resulting elements = dot product of the rows of the 1st matrix with the columns of the 2nd matrix

Type the following: >>a=[2 3] >>b=[3 2] >>a*b >>a.*b >>a.*b’ >>a*b’ Vector Multiplication

String Arrays Created using single quote delimiter (') Indexing is the same as for numeric arrays

String Array Concatenation

Working with String Arrays

Example: Solving Equations Solve this set of simultaneous equations: Ax=B, x=?

Creating Scripts with MATLAB Editor/Debugger Automatically saves files as ASCII text files for you. Scripts in MATLAB has the ".m" suffix. They are also called "M-files". Open Matlab Editor: File New M-file OR: >> edit Run

Add path >> addpath C:\EMEM899\Somedirectory Set path

Script M-files Standard ASCII text files Contain a series of MATLAB expressions A script does not define a new workspace % Comments start with "%" character pause % Suspend execution - hit any key to continue. keyboard % Pause & return control to command line. % Type "return" to continue. break % Terminate execution of current loop/file. return % Exit current function % Return to invoking function/command line. Continue % go to next iteration Input % Prompt for user input % Comments start with "%" character pause % Suspend execution - hit any key to continue. keyboard % Pause & return control to command line. % Type "return" to continue. break % Terminate execution of current loop/file. return % Exit current function % Return to invoking function/command line. Continue % go to next iteration Input % Prompt for user input

A Simple Script % a simple MATLAB m-file to calculate the % square root of an input numbers. my_num=input( ' insert a number ' ); % now calculate the square root of the number and print it out: square_root = sqrt(my_num) Write a program which receives a number from the user, calculates it’s square root (use ‘sqrt’ command) and displays the result. save the script as "square_root_script.m" in your own folder

Running Scripts >> square_root_script The header - comments you place at the beginning of your scripts will be returned to users when they get help for your script. >> help square_root_script Note: The variables defined in the script remain in the workspace even after the script finishes running. Creating comments: ctrl+r, or right click on the mouse, or %{ coment %}

Find and Replace – ctrl+F Key words Wrong use of key words Indenting: Ctrl+I Running Scripts (2)

Flow Control Constructs Logic Control: – IF / ELSEIF / ELSE – SWITCH / CASE / OTHERWISE Iterative Loops: – FOR – WHILE

The if, elseif and else statements if I == J A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end if I == J A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end Works on Conditional statements Logic condition is ‘true’ if its different then 0. ELSEIF does not need a matching END, while ELSE IF does. if I == J A(I,J) = 2; else if abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end %else if end %if if I == J A(I,J) = 2; else if abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end %else if end %if

Boolean Operators & Indexing

Switch, Case, and Otherwise switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end More efficient than elseif statements Only the first matching case is executed

Problem Build a program which receives a variable x and its units (mm, cm, inch, meter) and calculates Y- it’s value in centimeters units. Use switch case. 1 Inch = 2.54 cm Write a comment for error case. Save the file under units.m

Solution x = 3.0; units = 'mm'; switch units case {'in','inch'} y = 2.54*x % converts to centimeters case {'m','meter'} y = x*100 % converts to centimeters case { 'millimeter','mm'} y = x/10; disp ([num2str(x) ' in ' units ' converted to cm is :' num2str(y)]) case {'cm','centimeter'} y = x otherwise disp (['unknown units:' units]) y = nan; end x = 3.0; units = 'mm'; switch units case {'in','inch'} y = 2.54*x % converts to centimeters case {'m','meter'} y = x*100 % converts to centimeters case { 'millimeter','mm'} y = x/10; disp ([num2str(x) ' in ' units ' converted to cm is :' num2str(y)]) case {'cm','centimeter'} y = x otherwise disp (['unknown units:' units]) y = nan; end

Similar to other programming languages Repeats loop a set number of times (based on index) Can be nested Each loop is closed with end. The for loop N=10; for I = 1:2:N for J = 1:N A(I,J) = 1/(I+J-1); end N=10; for I = 1:2:N for J = 1:N A(I,J) = 1/(I+J-1); end

The while loop I=1; N=10; while I<=N J=1; while J<=N A(I,J)=1/(I+J-1); J=J+1; end I=I+1; end I=1; N=10; while I<=N J=1; while J<=N A(I,J)=1/(I+J-1); J=J+1; end I=I+1; end Similar to other programming languages Repeats loop until logical condition returns FALSE. Can be nested. Stopping infinity loop: Ctrl+C Ctrl+break

Array Operations

Line Plots in Two Dimensions Plot (x,y) makes a two-dimensional line plot for each point in X and its corresponding point in Y: (X(1),Y(1)), (X(2),Y(2)), (X(3),Y(3)), etc., and then connect all these points together with line. Example: >> x=1:1:5; >>Y=[ ]; >> plot (x,y); >> xlabel (‘label for x-axis’) >> ylabel (‘label for y-axis’) >> title (‘title’)

Check the following: x_points = [-10 :.05 : 10]; plot(x_points, exp(x_points)); % plot in Blue (default) grid on hold on plot(x_points, exp(.95.* x_points), 'm'); % plot in Magenta plot(x_points, exp(.85.* x_points), 'g'); % plot in Green plot(x_points, exp(.75.* x_points), 'p'); % plot a star hold off xlabel('x-axis'); ylabel('y-axis'); title('Comparing Exponential Functions'); legend ('1', '2', '3', '4') Multiple Plots

Subplots multiple plots in the same window, each with their own axes. Subplot (M,N,P) M – rows N - columns P – number of subplot in the figure Subplot (2,2,1)

More about figures Figure % Open a new figure without closing old figures Figure (i) % Open the i-th figure Close all % close all open figures axis ([xmin xmax ymin ymax]) % sets scaling for the x- and y-axes on the current plot.

Special Graph Annotations (TeX)

Plot Editor Toolbar

Exercise x = (1, 1.05, 1.1, 1.15… 5) Y=sin(x) Z=log(x) Put your name in the title Hint: check the doc on function “LineSpec”. Create the following:

Solution x=1:0.05:5; y=sin(x); z=log(x); hold on plot (x,y,'-.r*') plot (x,z,'-.go') hold off title ('Merav''s graph'); xlabel ('x') ylabel ('y') legend ('sin(x)', 'log(x)');

More exercise Make a 3 three-dimensional graph of (x,y,z) – use Matlab help. Make two separate 2-D graphs, with separate axis, in the same window: y vs. x, and z vs. x. Use the same x,y,z as defined in the previous exercise

Solution 3-D graph: >> plot3(x,y,z) >> grid >> xlabel ('x') >> ylabel('y') >> zlabel('z') >> title ('3D graph') Subplots >> subplot (1,2,1); >> plot(x,y); >> title ('sin(x)'); >> xlabel('x'); >> ylabel('y=sin(x)'); >> grid; >> subplot (1,2,2); >> plot(x,z); >> xlabel('x'); >> title ('log(x)'); >> grid; >> ylabel ('z');