Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group

Slides:



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

Lab # 03- SS Basic Graphic Commands. Lab Objectives: To understand M-files principle. To plot multiple plots on a single graph. To use different parameters.
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Introduction to MATLAB The language of Technical Computing.
Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.
Loading Excel Double click the Excel icon on the desktop (if you have this) OR Click on Start All Programs Microsoft Office Microsoft Office Excel 2003.
The Web Warrior Guide to Web Design Technologies
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
Graphics in MATLAB Week 15 – 5/5/09 Kate Musgrave
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to MATLAB Simon O’Keefe Non-Standard Computation Group
Programming in MATLAB Week 14 – 4/28/09 Kate Musgrave
Introduction to MATLAB MECH 300H Spring Starting of 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 Jianguo Wang CSSCR September 2009.
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.
MATLAB Fundamentals.
© 2002 ComputerPREP, Inc. All rights reserved. Word 2000: Working with Long Documents.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
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.
Python Programming Fundamentals
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.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
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.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
GUI development with Matlab: GUI Front Panel Components 1 GUI front panel components In this section, we will look at -GUI front panel components -Programming.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
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
Just as there are many human languages, there are many computer programming languages that can be used to develop software. Some are named after people,
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
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)
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
GUI development with Matlab: GUI Front Panel Components GUI development with Matlab: Other GUI Components 1 Other GUI components In this section, we will.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
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.
Files: By the end of this class you should be able to: Prepare for EXAM 1. create an ASCII file describe the nature of an ASCII text Use and describe string.
Introduction to Matlab
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
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 Lecture 5 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
Python Lesson 1 1. Starter Create the following Excel spreadsheet and complete the calculations using formulae: 2 Add A1 and B1 A2 minus B2 A3 times B3.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
“Moh’d Sami” AshhabSummer 2008University of Jordan MATLAB By (Mohammed Sami) Ashhab University of Jordan Summer 2008.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
An Introduction to Programming in Matlab Emily Blumenthal
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Computer Application in Engineering Design
Chapter 4 MATLAB Programming
Basic operations in Matlab
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB: Structures and File I/O
MATLAB Tutorial Dr. David W. Graham.
funCTIONs and Data Import/Export
Loop Statements & Vectorizing Code
INTRODUCTION TO MATLAB
Using Script Files and Managing Data
Introduction to MATLAB
Loop Statements & Vectorizing Code
Presentation transcript:

Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group

Content Writing scripts Flow control Writing and using functions Using cell arrays Creating structure arrays Plotting data 2

1 Scripts 3

Instead of typing each command into Matlab you can store them in a file known as a script To execute the commands in a script, type it’s name into the command prompt Within the script, you have access to variables defined in the workspace. Comments are denoted using the % symbol. Anything written after % is ignored by Matlab mresult = mean(results) % calculate the mean of the data 4

1 Scripts 5 To create a new script you can use the edit command >> edit This can also be used to open an existing script >> edit script_name Save the script, the filename will be the name of the script To run the script type the name into the command prompt >> script_name

2 Flow control 6

For command  Use a for loop to repeat one or more statements  The end keyword tells Matlab where the loop finishes  You control the number of times a loop is repeated by defining the values taken by the index variable  This uses the colon operator again, so index values do not need to be integer For example  >> for i = 1:4 a(i) = i * 2 end 7

2 Flow control  The counter can be used to index different rows or columns  E.g. >> results = rand(10,3) >> for i = 1:3 m(i) = mean(results(:, i)) end ..although you could do this in one step m = mean(results); 8

m(2) = mean(results(:, 2))m(3) = mean(results(:, 3)) i = 2i = 3 2 Flow control >> for i = 1:3 m(i) = mean(results(:, i)) end 9 i = 1 m(1) = mean(results(:, 1))

2 Flow control >> data = [ ] >> cat = [ ] To work out the mean for each category you could type 3 commands: >> mdata(1) = mean(data(cat == 1)) >> mdata(2) = mean(data(cat == 2)) >> mdata(3) = mean(data(cat == 3))  Which is OK when there are a few categories but any more would create a lot of work You can use a for loop instead >> for i = 1:3 mdata(i) = mean(data(cat == i)) end  The variable mdata will consist of 3 elements containing the mean of the values in data. The first element will contain the mean for category 1, second element the mean for category 2 and so forth. 10

mdata(3) = mean(data(cat == 3))mdata(1) = mean(data(cat == 1))mdata(2) = mean(data(cat == 2)) 2 Flow control >> for i = 1:3 mdata(i) = mean(data(cat == i)) end 11 i = 2i = 3i = 1

2 Flow control The ‘ if ’ command is used with logical operators Again, the end command is used to tell Matlab where the statement ends. For example, the following code loops through a matrix performing calculations on each column  >> for i = 1:size(results, 2) m = results(:, i) if m > 1 do something else do something different end 12

2 Flow control 13

2 Flow control The ‘while’ command >> while statement commands end Waiting Reading 14 >> fid = fopen(‘results.txt'); fline = ‘’; while tline ~= -1 disp(tline) tline = fgetl(fid); end fclose(fid); >> while mean(results) > 10 ind = results ~= max(results) results = results(ind) end

2 Flow control We can use flow control to display results for each of several experiments on separate plots. 15 mresult = mean(results) for i = 1:3 figure plot(results(:, i), ‘b.-’) hold on plot([1:10], repmat(mresult(i), 1, 10), ‘r-’) hold off end

2 Flow control If we use flow control in a script we do not know the size of the results matrix when it will be run. Instead, we make the script more general: 16 mresult = mean(results) for i = 1:size(results, 2) figure plot(results(:, i), ‘b.-’) hold on plot([1:size(results, 1)], repmat(mresult(i), 1, size(results,1)), ‘r-’) hold off end

3 Functions 17

3 Functions More functions:  pca – calculates the principle components of a set of data  fft– performs the fast Fourier transform on a data set  var – calculates the variance of the data  repmat – replicates a matrix  numel – returns the number of elements in a vector (or matrix)  cumsum – calculates the cumulative summation  sort – sorts a vector into ascending order  floor & ceil – rounds data values down or up to the nearest whole value  A list of the core functions that are available is located in Matlab’s help section. (Help Menu -> Matlab Help, in the right part of the window there is a Functions link) 18

3 Functions >> sortrows(data, col) 19

3 Functions Some functions can return two or more outputs. If this is the case use the following command structure >> [output1, output2] = function_Name(input1) For example >> rows = size(results) Could be written: >> [rows, cols] = size(results) 20

3 Functions To find out what outputs a function can return use the help command 21

3 Functions >> [sdata, ind] = sortrows(data, col) 22

3 Functions The function xlsread reads data from an Excel spreadsheet >> [num, text] = xlsread(filename, sheet, ‘range’)  Only the filename parameter is required, the others are optional  The text output is optional, if it is not used only the data from the spreadsheet is loaded 23

3 Functions 24

3 Functions You can create your own function if you need to use some calculation that is not provided by Matlab. This done in a similar way to creating a script; use the same edit command to edit a function.  >> edit function_Name 25

3 Functions The flow of a function is the same as a script; commands are carried out in the order that they appear and loops can be used. However, a function does not have access to variables in the workspace. Instead, you pass the data to the function. And once the function has finished it returns it’s results back to the output variable used when you called the function. Any variables you create within the function are deleted. 26

3 Functions When writing a function the first line must always be in the form: function [outputvariable, outputvariable2] = function_Name(inputvariable1, inputvariable2) This line tells Matlab the name of the function and how it can be used  The function name must match the file name  The output variable must be assigned a value inside the function.  The input variables can be accessed inside the function using their names. 27

3 Functions The function: function m = mymean(data) m = sum(data)./ size(data, 1) Can be used in a script or at the command prompt using: >> cm = mymean(data) 28

4 Cell Arrays 29

4 Cell Arrays Standard arrays hold 1 value per element which is ideal for storing results However, if you try to store a string, each letter is treated as a vector element For example  >> str = ‘subject1’ [s, u, b, j, e, c, t, 1]  >> str = [‘subject1’, ‘subject2’] [s, u, b, j, e, c, t, 1, s, u, b, j, e, c, t, 2]  >> str(1) ‘s’ Strings can not be stored and organised easily in vectors or matrices Cell arrays allow you to do this 30

4 Cell Arrays A cell array is similar to a normal array except that each cell can contain a whole array or vector (or a single value) And the item in each cell does not need to be the same size or even the same type Curly brackets are used to define cell arrays  All other operations work the same as with a normal array except that you use curly brackets instead of round brackets For example: >> labels = {‘string1’, ‘string2’, ‘string3’} >> labels{1} ‘string1’ 31

5 Plots 32

5 Plots Saving plots to a file >> print(fileformat, filename) file format: ‘-dbitmap’ ‘-depsc’ You can also achieve this using the File -> Save menu in the figure’s window The command line version is useful when you want to generate a lot of plots in a script which are saved automatically 33

5 Plots >> for i = 1:numel(results) figure plot(results(i).data, ‘b.-’) hold on plot([1:size(results(i).data)], repmat(results(i).mdata), ‘r-’) hold off print(‘-bmp’, [‘c:\users\tom\desktop\’, results(i).label]) end 34

5 Plots Subplots  Multiple plots can be placed within the same window  This is achieved using the subplot command  The window is split into a grid the size of which is specified when entering the command >> subplot(2,2,1) This creates a grid 2 x 2 in size (4 plots) and sets the current plot to the first of these. 35

5 Plots >> subplot(2,2,1)

5 Plots >> figure cols = 4 rows = ceil(numel(results) / cols) for i = 1:numel(results) subplot(rows, cols, i) plot(results(i).data, ‘b.-’) hold on plot([1:size(results(i).data)], repmat(results(i).mdata), ‘r-’) hold off end 37

5 Plots 38

5 Plots Handles allow you to create a plot and then edit the properties later. A handle is created when you create a plot or an object within the plot (for example title, legend) >> h = plot(data) This returns a handle to the line/s plotted, now you can change the line style, colour, width etc. The handle is stored in a variable which can then be used to edit the properties with the set command For example, the position of a plot’s legend can be changed using handles >> plot(data) >> h = legend('line') >> set(h,'Location','South') 39

5 Plots Inside/outside Best/Bestoutside 40 NorthwestNortheastNorth SouthSoutheastSouthwest EastWest

5 Plots Colour bars can be repositioned in the same way: >> h = colorbar >> set(h, ‘Location’, ‘North’) 41

5 Plots The figure function also returns a handle, you can use the set function to change the figure title:  >> h = figure  >> set(h, 'Name', 'Subject1') 42

5 Plots Surface plot >> surf(matrix) >> colorbar >> axis([ ]) >> title('Surface Plot'); >> xlabel('x') >> ylabel('y') >> zlabel('z') 43

5 Plots Contour >> contour(data) >> colorbar >> xlabel('x') >> ylabel('y') >> zlabel('z') >> title('Contour Plot'); >> axis([ ]) 44

5 Plots All of these can be use in conjunction with subplot, therefore, you can display several different plot types in one figure 45