Lesson 4 Arrays in MATLAB First round Lecturer : Dr. Noam Amir Format Revised. 01-11-2007 CE2002-NTUST.

Slides:



Advertisements
Similar presentations
CS 450: COMPUTER GRAPHICS LINEAR ALGEBRA REVIEW SPRING 2015 DR. MICHAEL J. REALE.
Advertisements

Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to arrays
Lecture 4.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 3.
Introdução ao M ATLAB M ATLAB Basico
Matrix Algebra Matrix algebra is a means of expressing large numbers of calculations made upon ordered sets of numbers. Often referred to as Linear Algebra.
Matrix Algebra Matrix algebra is a means of expressing large numbers of calculations made upon ordered sets of numbers. Often referred to as Linear Algebra.
SOLVING SYSTEMS OF LINEAR EQUATIONS. Overview A matrix consists of a rectangular array of elements represented by a single symbol (example: [A]). An individual.
Refresher: Vector and Matrix Algebra Mike Kirkpatrick Department of Chemical Engineering FAMU-FSU College of Engineering.
Arrays Revisited Selim Aksoy Bilkent University Department of Computer Engineering
Lecture 4 Sept 8 Complete Chapter 3 exercises Chapter 4.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
CIS 101: Computer Programming and Problem Solving Lecture 2 Usman Roshan Department of Computer Science NJIT.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
Eilon Sharon, Weizmann 2008 © 1 Introduction to Matlab & Data Analysis Tutorial 2: Variables and Matrix Manipulation.
Review of Matrix Algebra
GG313 Lecture 12 Matrix Operations Sept 29, 2005.
ECIV 520 Structural Analysis II Review of Matrix Algebra.
Lecture 6 Sept 15, 09 Goals: two-dimensional arrays matrix operations circuit analysis using Matlab image processing – simple examples.
EGR 106 – Week 4 – Math on Arrays
Concatenation MATLAB lets you construct a new vector by concatenating other vectors: – A = [B C D... X Y Z] where the individual items in the brackets.
MOHAMMAD IMRAN DEPARTMENT OF APPLIED SCIENCES JAHANGIRABAD EDUCATIONAL GROUP OF INSTITUTES.
Matlab Intro. Outline Matlab introduction Matlab elements Types Variables Matrices.
Lecture 4 Sept 7 Chapter 4. Chapter 4 – arrays, collections and indexing This chapter discusses the basic calculations involving rectangular collections.
Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating.
Part 3 Chapter 8 Linear Algebraic Equations and Matrices PowerPoints organized by Dr. Michael R. Gustafson II, Duke University All images copyright © The.
Matrix Mathematics in MATLAB and Excel
Lecture 7: Matrix-Vector Product; Matrix of a Linear Transformation; Matrix-Matrix Product Sections 2.1, 2.2.1,
1 Chapter 3 Matrix Algebra with MATLAB Basic matrix definitions and operations were covered in Chapter 2. We will now consider how these operations are.
Chapter 7 Matrix Mathematics Matrix Operations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Chapter 10 Review: Matrix Algebra
ECON 1150 Matrix Operations Special Matrices
MATLAB Basics With a brief review of linear algebra by Lanyi Xu modified by D.G.E. Robertson.
Matlab tutorial course Lesson 2: Arrays and data types
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
 Row and Reduced Row Echelon  Elementary Matrices.
M ATLAB Tutorial Course 1. Contents Continued  Desktop tools  matrices  Logical &Mathematical operations  Handle Graphics  Ordinary Differential.
1 M ATLAB Short Course. History of Calculator 2 3 Introduction to Matlab Matlab is short for Matrix Laboratory Matlab is also a programming language.
Introduction to MATLAB
Matlab Chapter 2: Array and Matrix Operations. What is a vector? In Matlab, it is a single row (horizontal) or column (vertical) of numbers or characters.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
Learner’s Guide to MATLAB® Chapter 2 : Working with Arrays.
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.
1 Lab 2 of COMP 319 Lab tutor : Shenghua ZHONG Lab 2: Sep. 28, 2011 Data and File in Matlab.
Linear algebra: matrix Eigen-value Problems Eng. Hassan S. Migdadi Part 1.
Working with Arrays in MATLAB
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
Chapter 2 Creating Arrays Legend: MATLAB command or syntax : Blue MATLAB command OUTPUT : LIGHT BLUE.
(The Transpose Operator) 1 >> C=[ ; ; ] C = >> D=C' D =
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Introduction to Engineering MATLAB – 4 Arrays Agenda Creating arrays of numbers  Vectors: 1-D Arrays  Arrays: 2-D Arrays Array Addressing Strings & String.
CS 450: COMPUTER GRAPHICS TRANSFORMATIONS SPRING 2015 DR. MICHAEL J. REALE.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
Finishing up Chapter 5. Will this code enter the if statement? G=[30,55,10] if G
Linear System of Simultaneous Equations Warm UP First precinct: 6 arrests last week equally divided between felonies and misdemeanors. Second precinct:
LAB 2 Vectors and Matrices Dr.Abdel Fattah FARES.
Matrices IB Mathematics SL. Matrices Describing Matrices Adding Matrices.
MAT 322: LINEAR ALGEBRA.
Linear Algebraic Equations and Matrices
Numeric, Cell and Structural Arrays One of the strenghts of MATLAB is the capabilty to handle collection of numbers called ARRAYS. MATLAB refers to scalars,
Chapter 7 Matrix Mathematics
Chapter 3 Arrays and Vectors
Linear Algebraic Equations and Matrices
Introduction to Programming for Mechanical Engineers (ME 319)
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
Matlab tutorial course
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
Presentation transcript:

Lesson 4 Arrays in MATLAB First round Lecturer : Dr. Noam Amir Format Revised CE2002-NTUST

Outline: Testing arrays in MATLAB The colon operator Concatenating arrays in MATLAB Array indexing Array math Sorting and searching in arrays

Working with Matrices MATLAB == MATrix LABoratory >> load durer >> image(X) >> colormap(map) >> load detail >> image(X) >> colormap(map)

Every variable is an array: >> a=1; >> size(a) ans = 1 1 >> length(a) ans = 1 >> a=1; >> size(a) ans = 1 1 >> length(a) ans = 1 Even a scalar Checking its dimensions: Checking on the number of elements: >> a=[1 2 3] a= >> size(a) ans = 1 3 >> length(a) ans = 3 >> a=[1 2 3] a= >> size(a) ans = 1 3 >> length(a) ans = 3 A vector can be a row or a column: >> a=[1; 2; 3] a= >> size(a) ans = 3 1 >> length(a) ans = 3 >> a=[1; 2; 3] a= >> size(a) ans = 3 1 >> length(a) ans = 3 row column

Entering Numeric Arrays >> a=[1 2;3 4] a = >> b = 2:-0.5:0 b = >> c = rand(2,4) c = >> a=[1 2;3 4] a = >> b = 2:-0.5:0 b = >> c = rand(2,4) c = Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] Matrices must be rectangular. (Undefined elements set to zero) Creating sequences using the colon operator (:) Utility function for creating matrices. (Ref: Utility Commands)

Entering Numeric Arrays - cont. >> w = [-2.8, sqrt(-7), (3+5+6)*3/4] w = i 10.5 >> x(3,2) = 3.5 x = >> w(2,5) = 23 w = i >> w = [-2.8, sqrt(-7), (3+5+6)*3/4] w = i 10.5 >> x(3,2) = 3.5 x = >> w(2,5) = 23 w = i Using other MATLAB expressions Matrix element assignment Any MATLAB expression can be entered as a matrix element

Some more about the colon (:) : >> 1:5 ans = >> a=5:1 a = Empty matrix: 1-by-0 >> 1:0.3:2 ans = >> 1:5 ans = >> a=5:1 a = Empty matrix: 1-by-0 >> 1:0.3:2 ans = Default step is 1 Impossible values are not an error If upper limit is not attainable – the values stop before it

Alternatives to the colon >> linspace(0,pi,5) ans= >> logspace(0,2,3) ans= >> logspace(0,1,10) ans= Columns 1 through Columns 7 through >> linspace(0,pi,5) ans= >> logspace(0,2,3) ans= >> logspace(0,1,10) ans= Columns 1 through Columns 7 through linspace and logspace: linspace(first,last,N) logspace(first_exp,last_exp,N)

Numerical Array Concatenation - [ ] >> a=[1 2;3 4] a = >> cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = >> a=[1 2;3 4] a = >> cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = Use [ ] to combine existing arrays as matrix “elements” Use square brackets [ ] 4*a Row separator: semicolon (;) Column separator: space / comma (,) Matrices must be rectangular.

Indexing into a vector: >> a=5:10 a = >> a(1) ans= 5 >> a(2:4) ans= >> a([1 3 2]) ans= >> a=5:10 a = >> a(1) ans= 5 >> a(2:4) ans= >> a([1 3 2]) ans= Indexing is done with parentheses A vector of indices is permissible Indexing is similar for row or column vectors >> a=(5:10)’ a = >> a(1) ans= 5 >> a(2:4) ans= >> a([1 3 2]) ans= >> a=(5:10)’ a = >> a(1) ans= 5 >> a(2:4) ans= >> a([1 3 2]) ans= Transpose

A matrix has more than one dimension - So an index into a matrix has to address each dimension separately, e.g.: mat(3,5) row column BUT: After all, a matrix is stored in memory as a string of elements And we can address that string of elements as a VECTOR! In other words – matrices in Matlab have schizophrenia… let’s have a look: Indexing into a matrix:

Indexing the Matrix in MATLAB A (2,4) A (17) Rectangular Matrix: Scalar:1-by-1 array Vector:m-by-1 array 1-by-n array Matrix:m-by-n array Matrix elements can be EITHER numbers OR characters

Array Subscripting / Indexing A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) Use () parentheses to specify index colon operator (:) specifies range / ALL [ ] to create matrix of index subscripts 'end' specifies maximum index value A(1:end,end) A(:,end) A(21:end)’

Matrix examples: >> a=[1 2;3 4] a = >> a(1,4)=5 % auto enlarging a = >> a(:,3)=[4; 4] a = >> b=a(:,4:-1:1) b = >> a=[1 2;3 4] a = >> a(1,4)=5 % auto enlarging a = >> a(:,3)=[4; 4] a = >> b=a(:,4:-1:1) b = >> b(6) % columnwise unraveling ans = 4 >> b(:) % columnwise unraveling ans = >> b(1,:)=[] % erasing a row b = >> b(6) % columnwise unraveling ans = 4 >> b(:) % columnwise unraveling ans = >> b(1,:)=[] % erasing a row b =

Matrices as vectors and vice versa: >> a=[1 2 3; 4 5 6] a = >> a(1:2) ans = 1 4 >> a(5) ans = 3 >> a(end) ans = 6 >> a=[1 2 3; 4 5 6] a = >> a(1:2) ans = 1 4 >> a(5) ans = 3 >> a(end) ans = 6 The previous pages showed that we can index into a matrix like a vector Unraveling is columnwise >> sub2ind(size(a),2,3) ans = 6 >> [r,c]=ind2sub(size(a),4) r = 2 c = 2 >> sub2ind(size(a),2,3) ans = 6 >> [r,c]=ind2sub(size(a),4) r = 2 c = 2 2 functions translate between the two types of indices:

Logical indexing: >> a=-3:3 a = >> abs(a)>1 ans = >> a(abs(a)>1) ans = >> a=-3:3 a = >> abs(a)>1 ans = >> a(abs(a)>1) ans = Logical operations give 0 or 1 The result of such operations is a logical array This kind of array can be used similarly to indexes - to retain or eliminate elements of a vector:

Logical indexing – cont.: >> a([ ]) % ouch! ??? Subscript indices must either be real positive integers or logicals. >> a(logical([ ])) ans = >> a([ ]) % ouch! ??? Subscript indices must either be real positive integers or logicals. >> a(logical([ ])) ans = An array that is composed of 1’s and 0’s isn’t necessarily a logical array A numeric array of 1 and 0 can be converted into a logical array using: logical()

Standard matrices: Some useful matrices can be created more easily: >> ones(2) ans = 1 1 >> ones(2,3) ans= >> rand(1,4) ans= >> diag([ 1 2 3]) ans = >> ones(2) ans = 1 1 >> ones(2,3) ans= >> rand(1,4) ans= >> diag([ 1 2 3]) ans = Makes a diagonal matrix from a vector diag Random numbers, gaussian distribution, zero mean, unit var. randn Random numbers, uniform distribution on [0,1] rand Identity matrix eye All 0 zeros All 1 ones

Size and length again: >> a=ones(3,4); >> size(a) ans = 3 4 >> size(a,1) ans = 3 >> size(a,2) ans = 4 >> a=ones(3,4); >> size(a) ans = 3 4 >> size(a,1) ans = 3 >> size(a,2) ans = 4 size gives a vector But we can obtain one element from it: >> a=ones(1,5); % row >> length(a) ans = 5 >> a=ones(5,1); % column >> length(a) ans = 5 >> a=ones(5,3,4); % 3D >> length(a) ans = 5 >> a=ones(1,5); % row >> length(a) ans = 5 >> a=ones(5,1); % column >> length(a) ans = 5 >> a=ones(5,3,4); % 3D >> length(a) ans = 5 length gives the length of a vector… But the maximum dimension of a matrix

Empty arrays: >> a=ones(3,4); >> numel(a) ans = 12 >> a=[] % empty variable a = [] >> numel(a) ans = 0 >> size(a) ans = 0 0 >> a=ones(3,4); >> numel(a) ans = 12 >> a=[] % empty variable a = [] >> numel(a) ans = 0 >> size(a) ans = 0 0 numel gives the number of elements in an array: >> a=zeros(0,3) a = Empty matrix: 0-by-3 >> size(a) ans = 0 3 >> length(a) ans = 0 >> numel(a) ans = 0 >> a(1,:)=[1 2 3] a = >> a=zeros(0,3) a = Empty matrix: 0-by-3 >> size(a) ans = 0 3 >> length(a) ans = 0 >> numel(a) ans = 0 >> a(1,:)=[1 2 3] a = BUT- an empty matrix can have a nonzero dimension:

Rearranging the dimensions: >> a=1:10; % 10 elements >> reshape(a,2,5) % 10 elements! ans = >> reshape(a,5,2) % 10 elements! ans = >> a=1:10; % 10 elements >> reshape(a,2,5) % 10 elements! ans = >> reshape(a,5,2) % 10 elements! ans = reshape takes the elements of an array and rearranges with new dimensions: >> a=[1 2;3 4]; >> repmat(a,1,2) ans = >> repmat(a,[1 2]) % same ans = >> repmat(a,2) % ‘2’ is extended ans = >> a=[1 2;3 4]; >> repmat(a,1,2) ans = >> repmat(a,[1 2]) % same ans = >> repmat(a,2) % ‘2’ is extended ans = repmat repeats an array

A word about transposing: The operator for transposing is the apostrophe (‘) Complex numbers are conjugated! For non-conjugating transpose, use: (.’) >> a=(5:7)+j a = i i i >> a’ ans= i i i >> a.’ ans= i i i >> a=(5:7)+j a = i i i >> a’ ans= i i i >> a.’ ans= i i i

Array sorting Matrices: each column is sorted separately: >> x=randperm(6) x = >> xs=sort(x) %ascending xs = >> [xs,ixs]=sort(x) %ascending xs = ixs = >> x=randperm(6) x = >> xs=sort(x) %ascending xs = >> [xs,ixs]=sort(x) %ascending xs = ixs = Vectors: >> m=[randperm(4);randperm(4);randperm(4)] m = >> [sm,ism]=sort(m) sm = ism = >> m=[randperm(4);randperm(4);randperm(4)] m = >> [sm,ism]=sort(m) sm = ism = Note: randperm(n) gives a random permutation of the integers from 1 to n

Array sorting – contd. >> m m = >> [tmp,ind]=sort(m(:,2)); >> % based on 2'nd column >> m(ind,:) ans = >> m m = >> [tmp,ind]=sort(m(:,2)); >> % based on 2'nd column >> m(ind,:) ans = Sorting all columns based on only one: >> [sm,ism]=sort(m,2) % add a dimension sm = ism = >> [sm,ism]=sort(m,2) % add a dimension sm = ism = Sort rows:

Searching in a vector: >> x=-3:3 x = >> k=find(abs(x)>1)% find indices where abs(x)>1 k = >> x(k)% extract those values ans = >> x(abs(x)>1)% logical addressing does the same thing ans = >> x=-3:3 x = >> k=find(abs(x)>1)% find indices where abs(x)>1 k = >> x(k)% extract those values ans = >> x(abs(x)>1)% logical addressing does the same thing ans = Searching in a vector is simple - find

Searching in a matrix: >> m=[ ; ] m = >> [ii,jj]=find(m>3)%one way ii = jj = >> m=[ ; ] m = >> [ii,jj]=find(m>3)%one way ii = jj = Same command - find >> ind=find(m>3)% another way ind = >> m(ind)=0 %replace with zeros m = >> m(ii,jj) % ouch!! ans = >> ind=find(m>3)% another way ind = >> m(ind)=0 %replace with zeros m = >> m(ii,jj) % ouch!! ans =

max imum and min imum in a vector: >> v=rand(1,6) v = >> max(v)% maximum ans = >> [mx,ind]=max(v)% maximum and index mx = ind = 5 >> min(v)% minimum ans = >> [mn,ind]=min(v)% minimum and index mn = ind = 4 >> v=rand(1,6) v = >> max(v)% maximum ans = >> [mx,ind]=max(v)% maximum and index mx = ind = 5 >> min(v)% minimum ans = >> [mn,ind]=min(v)% minimum and index mn = ind = 4

max imum and min imum in a matrix: >> m=rand(3,6)% maximum per column m = >> [mx,r]=max(m) mx = r = >> max(max(m)) % overall maximum – bad way ans = >> [mmx,ii]=max(m(:))% overall maximum – good way, with index! mmx = ii = 1 >> m=rand(3,6)% maximum per column m = >> [mx,r]=max(m) mx = r = >> max(max(m)) % overall maximum – bad way ans = >> [mmx,ii]=max(m(:))% overall maximum – good way, with index! mmx = ii = 1

Further manipulations: If any dimension is 1 – dimension is removed squeeze Extract lower diagonal from matrix (zero all that is above diagonal) tril Extract upper diagonal from matrix (zero all that is below diagonal) triu Extract diagonal from matrix diag(m) Make vector into a diagonal matrix diag(vec) Rotate 90 degrees twice counterclockwise rot(m,2) Rotate 90 degrees counterclockwise rot90 Flip array in left-right direction fliplr Flip array in up-down direction flipud

Array math in Matlab Linear algebra vs. simple algebra When performing mathematical operations between arrays in Matlab – how do we determine what rules will be used? Matlab has a set of rules that is generally simple and easy to follow Let’s examine the possible cases:

Scalar/Matrix math: >> w=[1 2;3 4] + 5 w = >> w=[1 2;3 4] + 5 w = Scalar expansion >> w=[1 2;3 4] = = = 8 9 >> w=[1 2;3 4] = = = 8 9 Generally this works for + - * / ^ …

Similarly: >> w=[1 2;3 4] * 5 w = >> w=[1 2;3 4] * 5 w = >> w=[1 2;3 4] / 5 w = >> w=[1 2;3 4] / 5 w = >> w=5 * [1 2;3 4] w = >> w=5 * [1 2;3 4] w = BUT: >> w=5 / [1 2;3 4] ??? Error using ==> mrdivide Matrix dimensions must agree. >> w=5 / [1 2;3 4] ??? Error using ==> mrdivide Matrix dimensions must agree. To resolve this we have to go a bit further…

Simple Matrix/Matrix math: >> w=[1 2;3 4] + [5 5;5 5] 6 7 = 8 9 >> w=[1 2;3 4].* [5 5;5 5] 5 10 = >> w=[1 2;3 4] + [5 5;5 5] 6 7 = 8 9 >> w=[1 2;3 4].* [5 5;5 5] 5 10 = Performing calculations element by element: Matrices must be the same size With + and – there is no ambiguity With other operators – add a dot:.*./.^ etc. >> w=5./ [1 2;3 4] >> w=5./ [1 2;3 4] … and to address the problem on the previous slide:

In this case: Matrices must have the same dimensions  imensions of resulting matrix = dimensions of multiplied matrices  Resulting elements = product of corresponding elements from the original matrices  Same rules apply for other array operations >> a = [ ; ]; >> b = [1:4; 1:4]; >> c = a.*b c = >> a = [ ; ]; >> b = [1:4; 1:4]; >> c = a.*b c = c(2,4) = a(2,4)*b(2,4)

NEXT: Matrix Multiplication and Division Multiplication:  I nner dimensions must be equal.  D imension of resulting matrix = outermost dimensions of multiplied matrices. Resulting elements = dot product of the rows of the 1st matrix with the columns of the 2nd matrix. >> a = [ ; ]; >> b = ones(4,3); >> c = a*b c = >> a = [ ; ]; >> b = ones(4,3); >> c = a*b c = [2x4] [4x3] [2x4]*[4x3] [2x3] a(2nd row).b(3rd column)

Division (solving equations): using “Left Division” To Solve the set of simultaneous equations: we need to calculate : >> A = [-1 1 2; ;-1 3 4]; >> b = [2;6;4]; >> x = inv(A)*b x = >> x = A\b x = >> A = [-1 1 2; ;-1 3 4]; >> b = [2;6;4]; >> x = inv(A)*b x = >> x = A\b x = x 1 + x 2 + 2x 3 = 2 3x 1 - x 2 + x 3 = 6 -x 1 + 3x 2 + 4x 3 = 4 x bA 

Some Matrix and Array Operators: >> help ops >> help matfun (In order of precedence) Matrix OperatorsArray operators () parentheses ’ comp. transpose.’ array transpose ^ power.^ array power * multiplication.* arraymult. / division./ array division \ left division + addition - subtraction Common Matrix Functions inv matrix inverse det determinant rank matrix rank eig eigenvectors & values svd singular value dec. norm matrix / vector norm

In most languages – you have to use loops: In MATLAB - use Array Operations instead: This kind of code is shorter and simpler IMPORTANT Example: Array Operations >> tic; for I = 1:10000 Density(I) = Mass(I)/(Length(I)*Width(I)*Height(I)); end; toc elapsed_time = >> tic; for I = 1:10000 Density(I) = Mass(I)/(Length(I)*Width(I)*Height(I)); end; toc elapsed_time = >> tic; Density = Mass./(Length.*Width.*Height); toc elapsed_time = 0 >> tic; Density = Mass./(Length.*Width.*Height); toc elapsed_time = 0 Use TIC and TOC to measure elapsed time Vectorized code WAS much faster than loops Before JIT!

Another example of loopless vs loopy code: Successive differences: Cumulative sum: >> a=1:10; >> for iii=1:9 b(iii)=a(iii+1)-a(iii); end >> b b = >> a=1:10; >> for iii=1:9 b(iii)=a(iii+1)-a(iii); end >> b b = >> diff(a) ans = >> diff(a) ans = >> cumsum(b) ans = >> cumsum(b) ans = looped loopless More about programming with arrays in a later lesson!

Summary: Arrays are very easy to use in MATLAB No declarations are necessary, and array dimensions can be modified dynamically Manipulating and indexing into arrays is very powerful, and can be complicated at times Arrays can be sorted and searched easily Math with arrays can be performed either element by element, or as defined by the rules of linear algebra