SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER 2014. Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.

Slides:



Advertisements
Similar presentations
Introduction to Matlab
Advertisements

Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
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
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.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Introduction to Matlab. I use Matlab for: Data analysis Data plotting Image Analysis Also – Simulations (solving odes/pdes/finite element methods) – Minimisations,
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/22/2003.
Programming in MATLAB Week 14 – 4/28/09 Kate Musgrave
MATLAB TUTORIAL Dmitry Drutskoy Some material borrowed from the departmental MATLAB info session by Philippe Rigollet Kevin Wayne.
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
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.
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.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
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 Session 1 Prepared By: Dina El Kholy Ahmed Dalal Statistics Course – Biomedical Department -year 3.
Introduction to Shell Script Programming
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. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
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.
Recap Graphic Window Edit Window Start Button Matrices in MATLAB Scalar Operations Order of Operations Array Operations Matrix Addition Matrix Multiplication.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
Introduction to MATLAB CBE 502 Mathematical Methods of Engineering Analysis.
MATLAB An Introduction to MATLAB (Matrix Laboratory) 1.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
Linux+ Guide to Linux Certification, Third Edition
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Recap Script M-file Editor/Debugger Window Cell Mode Chapter 3 “Built in MATLAB Function” Using Built-in Functions Using the HELP Feature Window HELP.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Introduction MATLAB stands for MATrix LABoratory.  Basics  Matrix Manipulations  MATLAB Programming  Graphics  Image types  Image Processing  Useful.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
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.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
General Computer Science for Engineers CISC 106 Lecture 13 - Midterm Review James Atlas Computer and Information Sciences 10/02/2009.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
Matlab for Engineers Matlab Environment Chapter 2.
Arrays. Topics to be Covered... Arrays ◦ Declaration ◦ Assigning values ◦ Array manipulation using loops Multi-dimensional arrays ◦ 2D arrays ◦ Declaration.
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
COMPUTER PROGRAMMING Year 9 – lesson 1. Objective and Outcome Teaching Objective We are going to look at how to construct a computer program. We will.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators.
Release Numbers MATLAB is updated regularly
Matlab Training Session 4: Control, Flow and Functions
Lecture: MATLAB Chapter 1 Introduction
Functions CIS 40 – Introduction to Programming in Python
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB: Structures and File I/O
User Defined Functions
Matlab review Matlab is a numerical analysis system
MATH 493 Introduction to MATLAB
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Functions continued.
Matlab Basics Tutorial
Presentation transcript:

SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER 2014

Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files. To edit files MATLAB contains a built in Editor which will help interpret MATLAB code in real time. Different code types will be different colors >> normal code >> keyword >> ‘string’ >> % comment Parsing errors will be highlighted in real time with the red squiggly underline while warnings will be highlighted with a golden squiggly line

MATLAB Screen

Scripts Scripts allow for complex series of commands to be run simultaneously one after the other. Useful for calculating and manipulating data Running the script will act as if you have entered every line in order into the command window, complete with unsuppressed responses Nonparsing errors will also appear along with the line where they occurred

Functions Function: Prewritten code that takes in inputs performs operations and then returns an output As we have seen MATLAB has a number of built in functions but you can also create you own Custom functions need to be saved with the same name as the function call Custom functions can only be run if they are in the current directory or one of the default directories for MATLAB

Directory Management To see what your current directory is use the cd function >> cd C:\Windows\system32 Your current directory can be managed by directly changing the file location cd can also be used to set the directory >> cd(‘C:\Users\Owner\Documents\ItM’)

Function Syntax The first evaluated line in a function must be the function call function [output1,output2,…] = FunctionName(input1,input2,…) You may have any number of inputs and outputs for a function but every output must be defined before the end of the function The final evaluated line should be the end keyword for every function

Subfunctions Only the first function in a function script can be called from outside of the function. This is because the filename is the same as the function However for complicated functions you may want to have a repetitive task be relegated to a subfunction. Subfunctions work just like a normal function in terms of syntax and you can have as many as you need.

Conditional Statements When creating functions you may only want to run certain section given a certain circumstances If statements help to accomplish this based on a conditional operator >> if a == 2 b = 3; end There are 6 main conditional operators; ==, ~=,, = If statements must be terminated with end just like functions To add additional conditions use else and elseif

Loops Loop: a repeated operation that ends depending on the type and a given circumstance The two main loop types are for loops and while loops For loops run for a set duration determined by the input variables >> for n = 1:100 b = n^2; end While loops will run until their conditional statement is met >> while a <= 29 a = a+3; end Loops must be terminated with end

Commenting For any script that you create, commenting is one of the most important things you can do. MATLAB Comments begin with the % sign >> % Anything written after this will be a comment >> % Comments show up highlighted in green and are not evaluated Comments are important as they help to explain what is going on A double % on its own line will also create sections inside a user generated script

Commenting A comment can also be added after code that is to be evaluated >> area = pi*2^2 % pi is a pregenerated variable equal to area = For most scripts the best practice is to use comment block for the first couple of lines detailing who wrote the script, when it was written and a brief description. The editor will automatically move the comment to a new line and auto comment if the description is long enough 1%% 2% Example Script 3% David Cooper 4% 7/9/14 5%5% 6% This is an example script created for the introduction to MATLAB course 7% it shows sever examples of useful function as well as some of the 8% prebuilt features for MATLAB code. 9%% 10

Structures Structures are organizational variables for storing other variables Structures can be initialized by assigning a variable to be equal to struct >> StructureExample = struct StructureExample = struct with no fields. Variables can be added to structs by delimitating with a period >> StructureExample.first = 1 StructureExample = first: 1

Saving Structures are useful for saving large numbers of variables easily The save() function will save your entire workspace or specific variables >> save(‘filename.mat’) >> save(‘filename.mat’, struct) Save filenames must have the extension.mat Using the load() function will load a.mat file into the current workspace. If you assign a variable then MATLAB will create a struct with the fields equal to the loaded variables >> load(‘filename.mat’) >> LoadedData = load(‘filename.mat’)

Useful Functions The numel() function is useful for determining the number of elements in a matrix or vector >> A = [1 2 3;4 5 6;7 8 9]; >> numel(A) ans = 9 The sum() function will sum up all of the elements along a single dimension. >> sum(A) ans = >> sum(sum(A)) ans = 45

Random Distributions There exist several useful random distributions that you may want to use. A uniform distribution involve an equal chance at existing at any of the numbers in the interval >> rand(n,m) >> unifrnd(a,b,n,m) A normal distribution observes the standard Gaussian curve with a mean and a standard deviation >> randn(n,m) >> normrnd(mu,sig,n,m) The second function for random is only available with the statistics toolbox

Averages MATLAB also has a number of built in functions for calculating averages. They work just like the sum() function in that the work one dimension at a time >> mean(A)>> median(A) ans = You can also calculate the standard deviation similarly >> std(A) ans = In order to calculate the average values for all of the elements simultaneously you must reshape the matrix into a vector

Min and Max MATLAB has built in functions to find the minimum and maximum for vectors and matrices >> max(A)>> min(A,[],2) ans = These functions can also be used to compare the elements to a specific number using the second input Min and max also have a second output that can be found by using a vector variable that contains the index for the corresponding return value >> [val, ind] = max(eye(3)) val = ind = 1 2 3

Rounding The round function will round a number or array to the nearest integer value >> B = [ ; ]; >> round(B) ans = To get a specific decimal place you must multiply the matrix by the power of 10 then divide the round answer by the same factor >> round(B*10)./10 ans = There is not a prebuilt function to do this otherwise but you can overwrite the round function to add this capability

Getting Help The help command allows you to get the MATLAB documentation for any function. It will also return a comment block from a custom function Visiting will give you the same information as in the help files but may be easier to navigatewww.mathworks.com/help/matlab Often someone else has tried the same thing you are. The MathWorks forums and file exchange will have community created functions that you can download and use Google is your friend. Typing ‘matlab’ plus whatever you are trying to do will often lead you strait to the related MATLAB function