Matlab It’s good. Variables Doubles (numbers) String (text) Cell: a 1x1 size space containing another variable, of any size, inside it Structure (struct):

Slides:



Advertisements
Similar presentations
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Advertisements

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.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
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.
JavaScript Switch Statement. Switch JavaScript Switch Statement If you have a lot of conditions, you can use a switch statement instead of an if…elseif…
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.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
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.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
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.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
If statements while loop for loop
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
>> x = [ ]; y = 2*x y = Arrays x and y are one dimensional arrays called vectors. In MATLAB all variables are arrays. They allow functions.
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.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Files Tutor: You will need ….
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
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.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
EEE 161 Applied Electromagnetics
Prof. Mark Glauser Created by: David Marr
Loops BIS1523 – Lecture 10.
© 2016 Pearson Education, Ltd. All rights reserved.
Matlab Training Session 4: Control, Flow and Functions
Chapter 4 MATLAB Programming
CSC 108H: Introduction to Computer Programming
Other Kinds of Arrays Chapter 11
Other Kinds of Arrays Chapter 11
Scripts & Functions Scripts and functions are contained in .m-files
JavaScript: Functions.
JavaScript: Control Statements.
Intro to PHP & Variables
MATLAB DENC 2533 ECADD LAB 9.
MATLAB: Structures and File I/O
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Arrays, For loop While loop Do while loop
Conditions and Ifs BIS1523 – Lecture 8.
Number and String Operations
Use of Mathematics using Technology (Maltlab)
MATLAB Tutorial Dr. David W. Graham.
Coding Concepts (Data Structures)
T. Jumana Abu Shmais – AOU - Riyadh
Chapter 8 Data Structures: Cell Arrays and Structures
Introduction to Matlab LAB 4
Python programming exercise
INTRODUCTION TO MATLAB
Note on Indexing of Array Elements
Objectives You should be able to describe: The while Statement
Selection Statements Chapter 3.
Python Review
Matlab Basics.
Chapter 8 Data Structures: Cell Arrays and Structures, Sorting
Class code for pythonroom.com cchsp2cs
Presentation transcript:

Matlab It’s good

Variables Doubles (numbers) String (text) Cell: a 1x1 size space containing another variable, of any size, inside it Structure (struct): a variable holding other variables attached to it

Variables: size Variables can be considered a martix. They are always at least 2-dimentional A variable with a single number has a size of 1x1 While a variable such as: Is 2 x 4 (rows x columns)

Accessing variable elements Variable elements can be accessed (or defined) by the variable name, followed by indices in brackets. Indices are (row, column) A(1,1) is 5, A(2,1) is 7, A(2,3) = 55 A(2,3) is row 2, third value. In a double variable, each number has a separate index A =

Defining Variables Variables are defined by an = sign E.g. A = 5.3 makes a 1x1 double with a value of 5.3 Now if we say A(1,2) = 6, we will have a 1x2 variable, [5.3 6] Try it!

Defining variables Several values can be entered aty once using square brackets [] A = [ ] gives a 1x5. A(1,5) is 7. You can also, in simple variables like this, just say A(5) A semi colon adds lines A = [ ; ] Must have the same number of elements per line

Padding with zeros Matlab will expand the size of variables as needed. In a double, zeros are padded as needed. A = 1 A(6) = 2 A is now

Colon operator In matlab, a colon has two meanings: – By itself, it means ‘all’ – With numbers on each side it means ‘from x to y’ E.g. 2:6 = You can use colons inside variable indexs when calling them E.g. A = [ ] B = A(3:5); B is now [6 8 10]

Colon wackiness A(1:5) = 10; Ai is now [ ] A = 1:5; A is now [ ] A = 2:2:10; the middle number becomes an incrimentor A is now

Exercise 1: defining double variables Make a double “A” with values 5, 10, 15, 20, 25, 30 Change the third value to 100 Make a variable “B” which is equal to the first 3 values in A Make a variable “C” which has the same value as the last value of A (by calling A, not cheating!) Pause here to contemplate the nature of existance

Exercise 1b: a matrix, using colons Clear – (this clears all variables from the matlab workspace) A = [ ; ; ] Set Change the 4 th value on the first row (the 9) to 3 Set B equal to the first row of A Set C equal to the first 3 numbers in the last row of A Set D as the first COLUMN of A

Error: In an assignment A(I) = B, the number of elements in B and I must be the same. Matlab tries to fit values into the exact space you define. If you tell it to fit 4 things in a space of 3 or 5 items, it throws an error: “In an assignment A(I) = B, the number of elements in B and I must be the same.” For example, A(3:5) = [1 2] – you are saying “in these 3 spaces, fit 2 things” If you give a single value for multiple spaces, Matlab sets them all to that values E.g. A(1:4) = 10, A is [ ].

Multiple Dimensions Matlab variables are always treated as if they were AT LEAST 2D, but can in fact have as much dimensionality as you wish. A third dimension can be thought of a cube. So: – A(:,:,1) = [1 2 3; 7 8 9] – A(:,:,2) = [ ; ] Now we have a 3D variable of size 2x3x2 Extra variables can be added (e.g. fMRI data is typically 4D): a cube, in a ‘room’

Basic Matlab Math Matlab treats double variables as matrices, and will often default to doing matrix math, if you provide it two matrices If you give a matrix an a mathmatical operand that is a single number, it applies that to all elements of a matrix E.g. A = [ ] B = A+2; B is now [ ] >

Calling matlab functions Matlab has thousands of useful functions you can call. A function call looks like this: Output = functionname(inputs, moreinput, etc) Output is any variable name into which the functions return value is assigned Multiple input values are separated by commas

HELP! All built-in matlab functions have a help. Type the word help and the function name Try “help sum” Lets try calling sum A = [ ]; B =sum(A) >> B is now 10 ( )

Sum part 2 Sum has an option to put in a second input variable. By default, sum outputs data for each row of the input A = [1 2 3; 4 5 6] Sum(a) gives [6 15] This is because by default it calls as sum(A,1), working on the sum based off the first dimension BUT sum(A,2) gives [5 7 9] (1+4, 2+5, 3+6)

Sum of sums, of more sums? Want sum? Since sum only works on one dimension, we can ‘nest it’ go get a total sum: B = sum(sum(A)) NOTE: brackets MUST be balanced!!!! B is now 21. Matlab evaluates functions inside-out. The ‘deepest’ thing gets evaluated first. > Other basic math functions: mean, min, max, median

Strings Matlab treats strngs as an array of charaters Strings are defined by encasing in single quotes A = ‘happy’ Now has a 1x6 variable A(2) is ‘a’ happy

String variables: size matters. a lot. One of the biggest issues with string variables is the issue of size during variable assignments. Matlab pads strings with whitespace When making lists, spaces at the end of names can be an issue (e.g. a list of file names to call) >

Strings are NOT numbers A = ‘1’ is a string, not a number A+1 is 50. Because when you do math on a string, it uses asci reference to the string. There are useful fucntions for this num2str str2num Examples!

Concatenating strings When we assigned double variables, we used square brackets. This can be thought of as concatenating a series of numbers We can also concatinate strings (or other variables) using [] E.g. direc = ‘/data/cool/fMRI/’ file = ‘nicebrain.nii’ fullfile = [direc file]

Cell: take a variable, and fit it into a space of 1x1 Cells are a type of ‘container’ variable to hold other variables. They can be especially useful for strings which can vary in length. Cells are defined by { } A{1} = [ ] gives a 1x1 sized cell. A(1) is a cell with a value { } A cell can be ‘extracted’ using curly braces B = A{1} gives a 1x4 double variable [ ]

Error: Cell contents assignment to a non-cell array object. If you tried the above code you got this This is because A is probably defined in your workspace as a string or double. You can only put a cell inside a cell variable Do some cell practice here

Saving variables Matlab always has a working directory, shown up top You can save data with the save command “Save mydata” will create a file names mydata.mat in the current directoy, with all variables from the workspace Load mydata will load this variable IF YOU ARE IN THAT DIRECTORY You can also specify a path – Load c:/scientceisfun/mydata.mat Or as a function call with a string – Load(‘c:/scientceisfun/mydata.mat’) Specific variables can also be saved (see help save)

Scripts and functions Matlab has a great editor which allows you to make scripts and functions Scripts just act as if you had copy/pasted the data into the main matlab windows Functions create a new workspace, and only have access to variables you send to it. – Functions do not modify variables in your main workspace, except the output variable!

Script example Type edit myscript His will open the editor with a file called myscript.m, which isn’t saved Type some commands in there and save Now if you type myscript in the matlab prompt, it will run those commands

Functions Functions are defined by having the word function on the first line, and the function call e.g. edit myfunc Function out = myfunc(in) Out = in* 10; Functions do not require an end statement or anything. They run line by line until the end A ‘return’ commend exists the function

Commenting scripts/functions Any content starting with a % is treated as a comment and not run A comment can be a while line, or after a command E.g. A = B %set A to B because SCIENCE Comments at the top of a function, immediately before the function line, will become the help for that function.

Basic complex syntax Most important things in matlab are completed via only the following steps: Define and cotnrol variables (covered, more or less) Calling functions (covered) If statements For/while loops

If statements In Matlab, if statements make code conditional The code following the if will only execute when the if condition is true For a mathmatical equals, use “==“, or “isequal” (which also works on strings) The if code applied until it hits an end statement

If example If A == 1 B=A; A = 2; end If A> 1 A = 1; end If A >=2 A = 1 end sSome allowable pp[erands: ==, >, =, ~= (not equal)

Else An if statements can also have else. In this case, when the ‘if’ is untrue, an ‘else’ will be run e.g. if A == 1 B=A; A = 2; else B =1; end

elseif Elseif runs a new if, ONLY when the first if is not true Can be chained Lower elseif only ever run if no above command is run Once any if/elseif is true, onlt that sub-block of code is run, and then it skips to the end startment

elseif example If a < 10 b = 1 elseif a > 100 b = 3 else %only runs if a is between 11 and 99 b = 2 end *there is no limit on the number of elseifs, though an else has to be the last condition. **In a chain of elseif’s it is possible none get run. If there is an if and else, at least one is going to run

For loops Probably the most important code in matlab Iterates a variable, usually a double for idx = 1:10 %is use idx by convention, any name is OK %code goes here end If can also call a variable Or a specified series of numbers, e.g. For ii = [ ] Like if, the loop terminates with an ‘end’ statement. A ‘break’ can also kill a loop

Loops in loops For loops and if statement can be nested count =1; for idx = 1:20 a(idx) = sum(b(idx,:)); if a(idx) > 100 for jdx = 1:5 c(idx,jdx) = a(idx) + jdx; end elseif a(idx) > 1000 break end %end of if d(idx) = a(idx); count = count+1; End %end for idx

While loops While works are in other programming formats, only running while/if the condition is true When it hits the end, it returns to the while and checks the condition n=1; a=1; while n < 10 a = a+b(n); %lets assume “b” was defined above somewhere if a < 10 n = n+1; end %end if end %will now check is n is still less than 10

Try and switch ‘try’ will try to run the code. If the code fails, instead of crashing matlab will go the end Switch allows testing multiple conditions switch method case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') end

Structure variable Structures are variables encasing other variables by name. Like pointers Attached “sub-variable” defined by a “.” e.g. A.dat = [1 2 3] Creates a struct variable A, with sub variable “dat” which is a 1x3 double. Structures are useful to save lots of data into a single variable, keeping thing organized Can be nested E.g. – a.dat.name = ‘funfun’ – a.dat.num = [ ]

Appendix of useful functions find disp length size