Getting started with MATLAB

Similar documents
CS129: Introduction to Matlab (Code)

Getting Started with MATLAB

Basics. Bilkent University. CS554 Computer Vision Pinar Duygulu

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

MATLAB TUTORIAL WORKSHEET

matlab_intro.html Page 1 of 5 Date: Tuesday, September 6, 2005

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

MATLAB Project: Getting Started with MATLAB

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Computer Project: Getting Started with MATLAB

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Getting started with MATLAB

Outline. User-based knn Algorithm Basics of Matlab Control Structures Scripts and Functions Help

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

MATLAB Project: Getting Started with MATLAB

Introduction. Matlab for Psychologists. Overview. Coding v. button clicking. Hello, nice to meet you. Variables

MATLAB Introductory Course Computer Exercise Session

Objectives. 1 Basic Calculations. 2 Matrix Algebra. Physical Sciences 12a Lab 0 Spring 2016

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

1 Introduction to Matlab

Lecture 2: Variables, Vectors and Matrices in MATLAB

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

An Introduction to MATLAB II

A General Introduction to Matlab

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Physics 326G Winter Class 2. In this class you will learn how to define and work with arrays or vectors.

Matlab Tutorial and Exercises for COMP61021

Introduction to MATLAB

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Introduction to MATLAB Practical 1

Introduction to MATLAB

Homework 1 Description CmpE 362 Spring Instructor : Fatih Alagoz Teaching Assistant : Yekta Said Can Due: 3 March, 23:59, sharp

Lecturer: Keyvan Dehmamy

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Laboratory 1 Octave Tutorial

AMS 27L LAB #2 Winter 2009

Applied Calculus. Lab 1: An Introduction to R

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

Chapter 1 Introduction to MATLAB

Matlab Tutorial for COMP24111 (includes exercise 1)

EGR 111 Introduction to MATLAB

Summer 2009 REU: Introduction to Matlab

Dr Richard Greenaway

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Introduction to MatLab. Introduction to MatLab K. Craig 1

Grace days can not be used for this assignment

Introduction to MATLAB

Introduction to Matlab. High-Level Computer Vision Summer Semester 2015

AN INTRODUCTION TO MATLAB

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

Computational Modelling 102 (Scientific Programming) Tutorials

FreeMat Tutorial. 3x + 4y 2z = 5 2x 5y + z = 8 x x + 3y = -1 xx

A QUICK INTRODUCTION TO MATLAB

Introduction to MATLAB programming: Fundamentals

Introduction to MATLAB

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Learning from Data Introduction to Matlab

To start using Matlab, you only need be concerned with the command window for now.

Getting To Know Matlab

Introduction to Matlab

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Introduction to Scientific Computing with Matlab

This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in

Introduction to MATLAB

Unix Computer To open MATLAB on a Unix computer, click on K-Menu >> Caedm Local Apps >> MATLAB.

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

Course Layout. Go to follow instr. Accessible within campus (only for the first download)

Introduction to Matlab

! The MATLAB language

Finding, Starting and Using Matlab

What is MATLAB and howtostart it up?

MATLAB Functions and Graphics

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has.

The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development

A Tutorial on Matlab Ch. 3 Programming in Matlab

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

MATLAB for beginners. KiJung Yoon, 1. 1 Center for Learning and Memory, University of Texas at Austin, Austin, TX 78712, USA

Matlab Lecture 1 - Introduction to MATLAB. Five Parts of Matlab. Entering Matrices (2) - Method 1:Direct entry. Entering Matrices (1) - Magic Square

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

MATLAB SUMMARY FOR MATH2070/2970

Introduction to Matlab

Intro to Matlab for GEOL 1520: Ocean Circulation and Climate or, Notions for the Motions of the Oceans

Chapter 2. MATLAB Fundamentals

Octave Tutorial Machine Learning WS 12/13 Umer Khan Information Systems and Machine Learning Lab (ISMLL) University of Hildesheim, Germany

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

Finding MATLAB on CAEDM Computers

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Stokes Modelling Workshop

Some elements for Matlab programming

QUICK INTRODUCTION TO MATLAB PART I

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Fall 2014 MAT 375 Numerical Methods. Introduction to Programming using MATLAB

Transcription:

Getting started with MATLAB You can work through this tutorial in the computer classes over the first 2 weeks, or in your own time. The Farber and Goldfarb computer classrooms have working Matlab, but it can be downloaded with your UNET id onto your laptop, as Brandeis has a site license. See: https://sites.google.com/a/brandeis.edu/matlab/student-computers and open the file within that page: matlab_insructions.pdf Be sure to click Academic Use (not Student Use ) when asked How will you use the Matlab software? Introduction to Matlab This course is adapted from MIT, Stanford, U Delaware Matlab crash courses. I have used the documents written by Stefan Roth and Tobin Driscoll besides the Matlab online tutorial. Azadeh Samadani 01/10/2007 Adapted more for BIOL135b and NBIO136b by Paul Miller 01/10/2009 Useful links: The Getting Started with MATLAB manual is a very good place to get a more gentle and thorough introduction: http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/ http://www.mathworks.com/academia/student_center/tutorials/ Basics: If you type in a valid expression and press Enter, MATLAB will immediately execute it and return the result, just like a calculator. >> 2+2 ans = 4 >> 4ˆ2 ans = 16 >> 1/0 Warning: Divide by zero. ans = Inf Notice the special expression here: Inf for. Another special value is NaN, which stands for not a number. NaN is used to express an undefined value. For example, >> Inf/Inf ans = NaN 5 2 * Challenge: Calculate the following statements:! =. Here are a few other demonstration statements. Anything after a sign is a comment. x = rand(2,2); ; means "don t print out result" s = Hello world ; single quotes enclose a string 1+

t = 1 + 2 + 3 +... 4 + 5 + 6...... means continue a line Here are a few useful commands: who cd pwd dir ls gives you your variables Change current working directory. Show (print) current working directory. List directory. List directory. * Type why in your command window Creating matrices and vectors A = [1 2; 3 4]; B = [1,2; 3,4]; N = 5 v = [1 0 0] v = [1; 2; 3] v = v' v = 1:0.5:3 v = pi*[-4:4]/4 v = [] Creates a 2x2 matrix The simplest way to create a matrix is to list its entries in square brackets. The ";" symbol separates rows; the (optional) "," separates columns. A scalar A row vector A column vector Transpose a vector (row to column or column to row) A vector filled in a specified range: [start:stepsize:end], brackets are optional Empty vector Creating special matrices 1ST parameter is ROWS, 2ND parameter is COLS m = zeros(2, 3) v = ones(1, 3) m = eye(3) v = rand(3, 1) m = zeros(3) Creates a 2x3 matrix of zeros Creates a 1x3 matrix (row vector)of ones Identity matrix (3x3) Randomly filled 3x1 matrix (column vector); see also randn Creates a 3x3 matrix (!) of zeros * Challenge: Create a 3x1 matrix with random elements between 0 and 5. (Hint: >>doc rand) Challenge: Find the row-wise sum of the elements of A. Find the column-wise product of the elements of A. (Hint: >>doc sum) Indexing vectors and matrices Warning: Indices always start at 1 and *NOT* at 0! v = [1 2 3]; v(3) Access a vector element

m = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] m(1, 3) Access a matrix element matrix(row #, COLUMN #) m(2, :) Access a whole matrix row (2nd row) m(:, 1) Access a whole matrix column(1 st column) m(1, 1:3) Access elements 1 through 3 of the 1 st row m(2:3, 2) Access elements 2 through 3 of the 2nd column m(2:end, 3) Keyword "end" accesses the remainder of a column or row m = [1 2 3; 4 5 6] size(m) Returns the size of a matrix size(m, 1) Number of rows size(m, 2) Number of columns m1 = zeros(size(m)) Create a new matrix with the size of m *Challenge: Create a 5x3 matrix with random elements and access the (3x2) elements on the lower right hand corner. (Hint: >>help end) Remember to check the help system often! It is really easy! If you know the command that you want to obtain some info about it is as easy as typing help command where command is the command that you are interested in. Simple operations and the dot modifier a = [1 2 3 4]'; A column vector 2 * a Scalar multiplication a / 4 Scalar division b = [5 6 7 8]'; Another column vector a + b Vector addition a - b Vector subtraction a.^ 2 Element-wise squaring (note the ".") a.* b Element-wise multiplication (note the ".") a./ b Element-wise division (note the ".") * Challenge: Define two arbitrary vectors A and B with same dimensions. Calculate A*B, A.*B and A*B? What is the answer to A/B and A./B? Which operations do not make sense? Vector operations Built-in Matlab functions that operate on vectors sum(a) mean(a) std(a) max(a) min(a) Sum of vector elements Mean of vector elements Standard deviation Maximum Minimum * Challenge: Without using a for loop, calculate the sum of all prime numbers less than 100. (Hint:>>help isprime) If a matrix is given, then these functions will operate on each column of the matrix and return a row vector as result

a = [1 2 3; 4 5 6] mean(a) max(a) max(max(a)) A matrix Mean of each column Max of each column Obtaining the max of a matrix Graphics (2D plotting) x = [0 1 2 3 4]; plot(x); pause plot(x, 2*x); axis([0 4 0 8]); figure; x = pi*[-24:24]/24; plot(x, sin(x)); xlabel('radians'); ylabel('sin value'); title('dummy'); figure; subplot(1, 2, 1); plot(x, sin(x)); axis square; subplot(1, 2, 2); plot(x, 2*cos(x)); axis square; figure; plot(x, sin(x)); hold on; plot(x, 2*cos(x), '--'); legend('sin', 'cos'); hold off; figure; m = rand(64,64); imagesc(m) colormap gray; axis image; axis off; Basic plotting Plot x versus its index values Wait for key press Plot 2*x versus x Adjust visible rectangle Open new figure Assign label for x-axis Assign label for y-axis Assign plot title Multiple functions in separate graphs (see "help subplot") Make visible area square Multiple functions in single graph '--' chooses different line pattern Assigns names to each plot Stop putting multiple figures in current graph Plot matrix as image Choose gray level colormap Show pixel coordinates as axes Remove axes You may zoom in to particular portions of a plot by clicking on the magnifying glass icon in the figure and drawing a rectangle. * Challenge: Plot functions x (blue squares and line), x^2 (red circles and line) and x^1/2 (green diamonds and line) between (0,2) on the same plot. Let s do Exercise 1! Creating scripts and functions using m-files Matlab scripts are files with ".m" extension containing Matlab commands. Variables in a script file are global and will change the value of variables of the same name in the environment of the current Matlab session. A script with name "script1.m" can be invoked by typing "script1" in the command window.

* Challenge: Create a script called myfirstscript.m to prints out today s date. (Hint: >>help date) Functions are also m-files. The first line in a function file must be of this form: function [out_1,..., out_m] = myfunction(in_1,..., in_n) The function name should be the same as that of the file (i.e. function "myfunction" should be saved in file "myfunction.m"). Have a look at myfunction.m for examples. a = [1 2 3 4]; b = myfunction(2 * a) >>a Global variable a Call myfunction which has local variable a function y = myfunction(x) Function of one argument with one return value a = [-2-1 0 1]; Have a global variable of the same name y = a + x; >>help myfunction Functions are executed using local workspaces: there is no risk of conflicts with the variables in the main workspace. At the end of a function execution only the output arguments will be visible in the main workspace. If we create a file named f.m in the current working directory with this code f.m function y = f(x, a) Returns the square of the first argument times the second y = a * x ^ 2; Then, from the command window we can just evaluate the function f(3, 4) ans = 36 In the command window type: >>help f * Challenge: Define a new function called stat.m that calculates the mean and standard deviation of a vector x. * Challenge: Define a new function called bellcurve.m that creates 10000 normally distributed random numbers with mean 3 and standard deviation 2. Make a histogram to verify the bell curve. (Hint:>> help randn and >>help hist) Syntax of flow control statements (for, while and if expressions) for VARIABLE = EXPR STATEMENT... STATEMENT end

EXPR is a vector here, e.g. 1:10 or -1:0.5:1 or [1 4 7] Example for loop to calculate 100 terms of the Fibonacci numbers, where each successive term is the sum of the two prior terms: Fibonacci.m clear clear all variables from the computer s memory Fib_seq(1) = 0; first two terms are defined as 1 and 1 Fib_seq(2) = 1; for i = 3:100 Fib_seq(i) = Fib_seq(i-1)+Fib_seq(i-2); end Fib_seq(1:10) plot(fib_seq) prints out the first ten terms for interest plots all 100 terms while EXPRESSION STATEMENTS end Example while loop for the Fibonacci numbers is almost (but not quite) identical: Fibonacci_while.m clear clear all variables from the computer s memory Fib_seq(1) = 0; first two terms are defined as 1 and 1 Fib_seq(2) = 1; i = 2; while( i < 100) i = i+1; Fib_seq(i) = Fib_seq(i-1)+Fib_seq(i-2); end Fib_seq(1:10) plot(fib_seq) prints out the first ten terms for interest plots all 100 terms if EXPRESSION STATEMENTS elseif EXPRESSION STATEMENTS else STATEMENTS end (elseif and else clauses are optional, the "end" is required) EXPRESSIONs are usually made of relational clauses, e.g. a < b The operators are <, >, <=, >=, ==, ~=

The following example code combines a for loop with an if expression to sum the multiples of 3 that are less than 100, and separately sum the nonmultiples: multiple_nonmultiple_sum.m sums multiples and nonmultiples of 3: sum_multiples = 0; sum_nonmultiples = 0; initialize sums to zero before accumulation for i = 1:99 all numbers less than 100 end if ( mod(i,3) == 0 ) if remainder is zero when dividing by 3 sum_multiples = sum_multiples + i; else sum_nonmultiples = sum_nonmultiples + i; end sum_multiples sum_nonmultiples * Challenge: Write a function that takes two variables and prints a statement indicating whether the first variable is smaller, larger, or equal to the second variable. * Challenge: Write a function that calculates! 3 2 ( n + n ) 200 0 More operations useful for HW Now you can perform some simple operations. Now let's implement a toy excercise that is somewhat similar to the homework. Suppose you want to write some code that tells you whenever some function, say a sinewave, has the value of 0.5 or greater. Off the top of my head, I can think of two basic ways to implement this: using a 'for' loop (the slow way), or using a few carefully chosen Matlab expressions. Both are fine for this course. First, let's look at a toy 'for' loop, and then we'll implement the procedure above using a 'for' loop. Type the following: for A=[1 2 3 4 5], A, end; for A=a, A, end; for A=1:5, A, end; All of these 'for' loops do the same thing. The variable A steps through the matrix [1 2 3 4 5], and inside the loop we have asked Matlab to display the value of A. We have defined the matrix [1 2 3 4 5] three different ways: explicitly, using our variable a as before, and a new way, using the colon operator. The colon operator allows you to define a vector as running from a beginning value to an ending value, and optionally using a step different from 1. Try this below:

A=1:5 A=5:-1:1 A=0:0.1:1 Now you should have a good grasp of the colon operator. Let's solve the problem we introduced at the beginning of the section with a 'for' loop and plot the result. T=0:0.01:10; define T to be a vector running between 0 and 10 in steps of 0.01 sw = []; define sw to be an empty vector th=[]; define an empty vector for determining if we are exceeding threshold or not for t=t, for each value of T sw(end+1) = sin(2*pi*t); set next value of sw to be the sine of 2*pi*t th(end+1) = sw(end)>0.5; add either a 1 or a 0 to th end; now let's plot figure(1); subplot(2,1,1); plot(t,sw); axis([t(1) T(end) -1.5 1.5]); subplot(2,1,2); plot(t,th); axis([t(1) T(end) -0.5 1.5]); set the axis so it looks prettier Here we've introduced two new operations. One is the idea of creating an empty vector and adding to it. If you want to see this more closely, type 'A=[], A(end+1)=1, A(end+1)=1,'. We've also introduced the comment syntax: any text on a line following a '' will not be treated as code. This will help you remind yourself what you have written, and will help the TAs grade your homework. Now let's do this same function in a way that takes advantage of Matlab's matrix style. First, let's use the 'clear' command to clear some of our old variables: clear T sw th T=0:0.01:10; sw=sin(2*pi*t); this does all values of T at once th = sw>0.5; this does all entries of sw at once now let's plot figure(1); subplot(2,1,1); plot(t,sw); axis([t(1) T(end) -1.5 1.5]); subplot(2,1,2); plot(t,th); axis([t(1) T(end) -0.5 1.5]); set the axis so it looks prettier So hopefully now you are begining to understand how Matlab's language can allow you to briefly perform some complicated manipulations. If you were doing actual homework, you would want to title these plots and label the y and x axes.