MATLAB 1. Jeff Freymueller September 24, 2009

Similar documents
Fundamental Programming Principles: Variables and Func6ons

Introduction to Programming for Biology Research

An Introduction to Matlab5

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

MATLAB TUTORIAL WORKSHEET

What is MATLAB and howtostart it up?

Introduction to Matlab. By: Hossein Hamooni Fall 2014

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

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

How to learn MATLAB? Some predefined variables

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

Introduction to MATLAB

Chapter 4: Programming with MATLAB

Introduction to Scientific Computing with Matlab

Introduc)on to Matlab

APPM 2460 Matlab Basics

Matlab Advanced Programming. Matt Wyant University of Washington

Chapter 1 Introduction to MATLAB

Introduction to MATLAB

MACRO NOTES DOCUMENTATION

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

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

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Cell Arrays, Struct Arrays, Matlab Path

Introduction to MATLAB

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

SIMPLE INPUT and OUTPUT:

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

EGR 111 Introduction to MATLAB

EGR 111 Functions and Relational Operators

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009)

Matlab- Command Window Operations, Scalars and Arrays

Getting started with MATLAB

Introduction to MATLAB

MATLAB Second Seminar

ENGR 1181 MATLAB 02: Array Creation

7 Control Structures, Logical Statements

Getting started with Matlab: Outline

User Defined Functions

EGR 111 Functions and Relational Operators

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

MATLAB GUIDE UMD PHYS401 SPRING 2011

SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK

EGR 102 Introduction to Engineering Modeling. Lab 05A Managing Data

Introduction to Scientific Computing with Matlab

Array Creation ENGR 1181 MATLAB 2

AMS 27L LAB #2 Winter 2009

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

Beyond the Mouse A Short Course on Programming

Introduction to Scientific Computing with Matlab

Dynamics and Vibrations Mupad tutorial

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

Stokes Modelling Workshop

Introduction to Matlab

An Introductory Tutorial on Matlab

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

Essentials for the TI-83+

Use JSL to Scrape Data from the Web and Predict Football Wins! William Baum Graduate Sta/s/cs Student University of New Hampshire

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

(Creating Arrays & Matrices) Applied Linear Algebra in Geoscience Using MATLAB

Matlab Introduction. Scalar Variables and Arithmetic Operators

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

University of Alberta

Last &me: Javascript (forms and func&ons)

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

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

McTutorial: A MATLAB Tutorial

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Introduction to MATLAB for Engineers, Third Edition

Lab 1 Introduction to MATLAB and Scripts

More on variables, arrays, debugging

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

Introduction to Matlab

Branches, Conditional Statements

Machine Learning Exercise 0

Desktop Command window

2 Amazingly Simple Example Suppose we wanted to represent the following matrix 2 itchy = To enter itchy in Matla

Mini-Matlab Lesson 5: Functions and Loops

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

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:

An Introduction to Programming in MATLAB Michael Sockin February 20, 2015

Getting Started with MATLAB

Introduction to Matlab. CSE555 Introduction to Pattern Recognition Spring 2011 recitation

Introduction to MATLAB Programming

Boolean Logic & Branching Lab Conditional Tests

FDP on Electronic Design Tools - Computing with MATLAB 13/12/2017. A hands-on training session on. Computing with MATLAB

Matlab and Psychophysics Toolbox Seminar Part 1. Introduction to Matlab

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning.

Time-Saving Hint: Use the up-arrow on your keyboard to cycle through old commands.

ECE Lesson Plan - Class 1 Fall, 2001

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

Dr Richard Greenaway

1 Introduction to MATLAB

Matlab Tutorial for COMP24111 (includes exercise 1)

C/C++ Programming for Engineers: Matlab Branches and Loops

SAMLab Tip Sheet #1 Translating Mathematical Formulas Into Excel s Language

Computer Vision. Matlab

ENGR 253 LAB #1 - MATLAB Introduction

Variables and Assignments

Transcription:

MATLAB 1 Jeff Freymueller September 24, 2009

MATLAB IDE

MATLAB Edi?ng Window

We don t need no steenkin GUI You can also use MATLAB without the fancy user interface, just a command window. Why? You can run MATLAB on a remote machine (fast) You can run a specific MATLAB program from a command line, or even automa?cally from a script Some people like it bever that way.

MATLAB MATLAB help MATLAB has a lot of help func?ons. First: help matlab General: help command There is also a graphical help browser. Access it from the Help menu or using doc command When you write your own func?ons, you can add comments that will appear when you type help my_func?on >> help if IF Condi?onally execute statements. The general form of the IF statement is IF expression statements ELSEIF expression statements ELSE statements END The statements are executed if the real part of the expression has all non zero elements. The ELSE and ELSEIF parts are op?onal. Zero or more ELSEIF parts can be used as well as nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=, or ~=. Example if I == J A(I,J) = 2; elseif abs(i J) == 1 A(I,J) = 1; else A(I,J) = 0; end See also RELOP, ELSE, ELSEIF, END, FOR, WHILE, SWITCH. Reference page in Help browser doc if

Some Good Habits You can copy lines from the command window or command history and paste them into an edi?ng window to save them. If you do anything important by typing into the command window, save your commands as a script for future reference and future use! You can write several lines of code in the edi?ng window, and then copy and paste them into the command window to try them out (just hit return aler the paste) Test out small, manageable pieces of your code! The run buvon in the edi?ng window is really handy for tes?ng the whole script or program. The edi?ng window has some great debugging features as well. Aler you have mastered the basics, learn how to use the debugger.

Variables in MATLAB MATLAB treats all variables as arrays (vectors or matrices). Program s roots are in linear algebra. Scalars are just 0 dimensional arrays (single values) Values assigned using = : a_row = [1 2 3] MATLAB displays the answer aler every command, unless you end the command with a semi colon. Most of the?me, you don t need to worry about the variable type, MATLAB handles it invisibly. But you do have to remember that there is a difference between a row vector and a column vector.

Matrix, Row Vector, Column Vector A matrix A row vector 1 0 0 0 1 0 0 0 1 [ 1 2 3] A column vector They are not the same: 1 2 3 1 [ 1 2 3] 2 =1+ 4 + 9 =14 3 1 2 1 2 3 3 [ ] = 1 2 3 2 4 6 3 6 9

Bracketology MATLAB uses three different kinds of brackets, parentheses, braces, all meaning different things [ ] Square brackets Vectors, arrays and matrices are contained inside ( ) Parentheses Access a par?cular element of an array by purng the indices inside parentheses { } Braces or Curly brackets Like parentheses, except for cell arrays

Array vs. Cell array Cell arrays behave a bit differently than regular arrays. Every element of a regular array must be the same kind. Not so for cell arrays. Each element of a cell array is a container that can hold any one thing. Cell arrays are really useful for strings, and also are returned by some func?ons that read files. You can do numerical opera?ons across regular arrays, but not cell arrays. You ll see more examples as we go along.

Special Numbers MATLAB handles complex numbers seamlessly 5 + sqrt( 1) = 5.0000 + 1.0000i If you do not define a variable i, MATLAB will use that symbol for sqrt( 1). Not a Number (NaN) is a very handy number Use NaN to represent missing values DO NOT use 9999 for missing values! Any arithme?c opera?on with NaN produces NaN The func?on isnan finds all the NaNs in its argument idx = isnan(has_a_nan)

Func?ons What is a func?on? A set of mathema?cal opera?ons that take some input values ( variables ) and produce an output value. Remember every value can be a scalar or a vector or matrix A livle black box of code that takes some inputs and produces one or more outputs Examples: sqrt, isnan, find, eye, zeros, ones, size, inv

Let s Explore MATLAB for a while Assigning variables Help Features of the IDE Some basic func?ons MATLAB is vectorized! Load and save. See also: xlsread, xlswrite csvread, csvwrite

Defining your own func?ons Save your func?on in its own.m file Start with a func?on declara?on output = func?on my_func(input1, input2) [out1, out2] = func?on two_out(in1, in2, in3) End with return (not required, but good habit) You can use any number of inputs and any number of outputs If you change the values of the input variables inside the func?on, those changes are lost when you exit The arguments to the func?on are passed by value Some languages (like fortran) pass arguments by reference, so you can change any variable passed to a subrou?ne/func?on Any comment lines immediately alerward are used by help

Scope of variables The func?on exists in its own separate livle space. It interacts with its calling rou?ne only through the arguments it is passed and the values it returns. It can only modify the values it returns, and not the arguments. Variables used inside the func?on are created when the func?on is called, and thrown out when it is done. You can re use variable names inside a func?on that are also used somewhere outside.

More of your own func?ons As long as MATLAB knows where to find it, your func?on becomes just as much a part of the language as the built in func?ons Build up a set of your own useful func?ons! MATLAB will always find func?ons in the current directory Use addpath to specify other directories where it should look for your func?ons Assemble small pieces into bigger tools! Be sure to use sensible names!

Exercises 3.1. Explore the help func?on, and start up the help browser from the Help menu, and using doc 3.2. Make a version of class_hasbugs.m that runs without errors. Save it as class_nobugs_yourname.m and email it to me. 3.3. Modify the func?on class_new_func?on. Define x = linspace(1, 10, 10). Then make a plot: plot(x, class_new_func?on(x)) 3.4. Define a new func?on of your own, in its own source file. Make it have reasonable values for a range of inputs. Plot it.

Structures Suppose you have a set of variables that go together. A structure (or struct) lets you package them together, making it easy to keep track of things. A struct has one or more fields, which are named, and each can store a value (or vector, or array, or a struct, or ) You define a struct by naming its fields and assigning a value to each (or use [] for an empty value). Access a field like this: weather.year, weather.temp(5) Or geyield(weather, year ) or geyield(weather, name) where name is a variable.

Let s Explore MATLAB for a while Structs Let s look at the?meseries struct This is an example of packaging a variety of related informa?on into one container If I want to store mul?ple?meseries, I could make a cell array and store each?meseries in one element.

Struct Example 2 Suppose you have a data set that has a number of arrays of the same size. There might also be some other informa?on. For each day of year, you have temperature, pressure and humidity readings What are the fields? Year (scalar) Day_of_year (array) temperature, pressure, humidity (arrays) In this case, it makes sense to make an array of structs, which will allow you to do some numerical opera?ons on the elements, like finding the minimum, maximum or mean.

Example 2 The easy way to make an array of structs is to put all the numerical values into cell arrays and use these to define the struct. Note: some input rou?nes give you the data in cell arrays already! You ll get an error message if the cell arrays are different sizes. weather = struct( year, 2009, day_of_year, {225, 230, 235}, temp, {64, 69, 58}, pressure, {30.1, 30.5, 29.5}, humidity, {0.64, 0.34, 0.88}); This produces a 3 element array of structs. You can access the values in different ways: weather(2).temp median( [weather.pressure] )

Let s Explore MATLAB for a while Structs Let s look at the weather struct This is an example of packaging several related variables, like a set of mul? variable observa?ons

Summary MATLAB has several different types of variables Scalars, vectors matrices Strings Structs Cell arrays MATLAB provides a handy environment for wri?ng code. MATLAB is actually very fast, especially for vectorized opera?ons.