Chapter 3 Arrays and Vectors

Slides:



Advertisements
Similar presentations
Multidimensional Array
Advertisements

Introduction to arrays
Introduction to Matlab
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
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.
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.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character 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.
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.
EGR 106 – Week 3 – More on Arrays Brief review of last week Additional ideas: – Special arrays – Changing an array – Some array operators – Character arrays.
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.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
Matlab tutorial course Lesson 2: Arrays and data types
Array Math.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
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.
A First Book of ANSI C Fourth Edition
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,
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.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
1 Lab 2 of COMP 319 Lab tutor : Shenghua ZHONG Lab 2: Sep. 28, 2011 Data and File in Matlab.
Introduction to Matlab Module #2 Page 1 Introduction to Matlab Module #2 – Arrays Topics 1.Numeric arrays (creation, addressing, sizes) 2.Element-by-Element.
Covenant College November 14, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Ch. 3: Vectors and Arrays.
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.
(The Transpose Operator) 1 >> C=[ ; ; ] C = >> D=C' D =
Array Operations ENGR 1181 MATLAB 4.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
EGR 115 Introduction to Computing for Engineers MATLAB Basics 1: Variables & Arrays Wednesday 03 Sept 2014 EGR 115 Introduction to Computing for Engineers.
CMPS 1371 Introduction to Computing for Engineers VECTORS.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
ECE 1304 Introduction to Electrical and Computer Engineering
Introduction to MATLAB for Engineers, Third Edition
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,
응용 전산 및 실습 MATLAB – Chapter 3 행렬연산
BASIC ELEMENTS OF A COMPUTER PROGRAM
© 2016 Pearson Education, Ltd. All rights reserved.
EGR 115 Introduction to Computing for Engineers
Introduction to Programming for Mechanical Engineers (ME 319)
2) Platform independent 3) Predefined functions
JavaScript: Functions.
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
EEE 244 Numerical Methods In Electrical Engineering
StatLab Matlab Workshop
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Matlab tutorial course
Vectors and Matrices I.
Introduction to MATLAB [Vectors and Matrices] Lab 2
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Array Creation ENGR 1181 MATLAB 02.
Loop Statements & Vectorizing Code
Spreadsheets 2 Explain advanced spreadsheet concepts and functions
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
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.
Spreadsheets Objective 6.02
Announcements P3 due today
CS 111 Introduction to Computing in Engineering and Science
Loop Statements & Vectorizing Code
Spreadsheets Objective 6.02
Math review - scalars, vectors, and matrices
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

Chapter 3 Arrays and Vectors CSE 1010 Chapter 3 Arrays and Vectors

Objectives  Learn about built-in MATLAB functions  Learn about data collections and how to: Create them Manipulate them Access their elements Perform mathematical and logical operations on them

Functions A function is a named collection of instructions that operates on the data provided to produce a result according to the use of that function For example, >> A = cos(angle) For help on a specific function, you can type >> help <function name> >> help sqrt SQRT Square root. SQRT(X) is the square root of the elements of X. Complex results are produced if X is not positive.

Data Collections Groups of data in specific structures arrays, vectors Using data collections allows us to: Refer to all the data together e.g., “all the temperature readings for May” Move data items around as a whole group Perform math or logical operations on the groups e.g., compute the average, maximum, or minimum temperature for the month

Data Collections, cont’d A homogeneous collection of data is constrained to accept only items of the same data type e.g., all numeric, all character

Arrays and Vectors grades 5 3 7 9 11 2 An array is a named collection of like data arranged into rows and columns A one-dimensional array (one row or one column) is called a vector (row vector, column vector) Values in the array are called elements An index identifies the position of an element (a value) in a vector Example: the vector called grades has 6 elements (is of size 6) grades 5 3 7 9 11 2 1 4 5 6 2 3

Creating a Vector – Constant Values (Declaring a Vector) 1 - Enter the values directly: e.g., A = [2, 5, 7, 1, 3] 2 - Enter the values as a range of numbers: e.g., B = 1:3:20 3 - Use the linspace(...) function: e.g., C = linspace (0, 20, 11) ans = 0 2 4 6 8 10 12 14 16 18 20  More on linspace on the next slide 4 - Use the functions zeros(1,n), ones(1,n), rand(1,n) and randn(1,n) to create vectors filled with 0, 1, or random values between 0 and 1 2 5 7 1 3

linspace >> help linspace LINSPACE Linearly spaced vector.     LINSPACE(X1, X2) generates a row vector of 100 linearly equally spaced points between X1 and X2.       LINSPACE(X1, X2, N) generates N points between X1 and X2.     For N < 2, LINSPACE returns X2.     Class support for inputs X1,X2:        float: double, single

Creating a Vector – Constant Values Entering the values directly, e.g. A = [2, 5, 7, 1, 3] Entering the values as a range of numbers e.g., B = 1:3:20 >> B = 1 4 7 10 13 16 19 Using the functions zeros(1,n), ones(1,n), rand(1,n) and randn(1,n) to create vectors filled with 0, 1, or random values between 0 and 1 >> vecZeros = zeros(1,5) vecZeros = 0 0 0 0 0 Ending number Starting number Increment 1-10

Array indexing Indexing means accessing or changing specific indexed values of an array Array index starts at 1  xLet k be the index of vector x, then k must be a positive integer 1 < = k < = length(x) length (x) = 6 To access the kth element: x(k) >> x(2) 8 >> x(4)=55 x 5 8 2 55 9 5 11 1 2 3 4 5 6

Array indexing Accessing beyond array length is illegal ??? … index out of bounds because… >> x(0) ??? … index must be a positive integer or logical. What does “logical” mean? Read your textbook, p.52. Ready for the next Quiz? Writing beyond array length will extend the vector automatically beyond its current end >> x(8)= 21 x 5 8 2 9 5 11 1 2 3 4 5 6 7 x 5 8 2 9 5 11 21 1 2 3 4 5 6 7 8

Add and Remove To add more than one element, create a new vector by concatenating elements >> x = [vecDirect 12, 14] x = 5 8 2 9 5 0 12 14 Removing elements >> x(6) = [] % an empty vector Not advisable because it can lead to logic problems when changing length of a vector x 5 8 2 9 5 12 14 1 2 3 4 5 6 7 8 x 5 8 2 9 5 12 14 1 2 3 4 5 6 7 8

Operations on vectors Basic operations are : Arithmetic operations Logical operations Applying library functions Concatenation Slicing (generalized indexing) First three extend from scalar operations, the rest are unique to vectors

Element-by-element Operations on Arrays + - .* ./ .^ You must use the dot (.) with these!

Element-by-element Operations on Arrays and Scalars + + - - * * / ./ .^ .^ You must use the dot (.) with these! You may use dot (.) with these, but not necessary

Multiplication … and Multiplication Mathematics http://easycalculation.com/matrix/learn-matrix-multiplication.php  Matlab http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/mtimes.html&http://www.google.com/search?hl=en&source=hp&q=%22matrix+multi%5Blication%22++matlab&aq=f&oq=&aqi=  

Arithmetic Operations Algebraic Syntax MATLAB syntax Addition a + b Subtraction a - b a – b Multiplication a x b a * b Division a ÷ b a /b Exponentiation ab a^b >> A = [6 4 2 1 8]; >> A + 5 ans = 11 9 7 6 13 >> A .* 3 % elt-by-elt multiplication 18 12 6 3 24 >> B = -1:1:3 B = -1 0 1 2 3

>> A .* B % Elt-by-Elt multiplication ans = -2 0 7 2 9 Operation MATLAB syntax Elt-by-elt Multiplication a .* b Elt-by-elt Division a ./b Elt-by-elt Exponentiation a.^b >> A = [2 5 7 1 3]; %B = -1 0 1 2 3 >> A .* B % Elt-by-Elt multiplication ans = -2 0 7 2 9 >> A * B % matrix multiplication!! ??? Error using ==> mtimes Inner matrix dimensions must agree. >> C = [1 2 3]; >> A .* C % A and C must have the same length ??? Error using ==> times Matrix dimensions must agree.

Logical Operations >> A = [2 5 7 1 3]; >> B = [0 6 5 3 2]; >> A > = 5 % check which elements of A > = 5 ans = 0 1 1 0 0 >> A > = B % check which elements of A > = B 1 0 1 0 1 >> C = [1 2 3] >> A > C ??? Error using ==> g t Matrix dimensions must agree. Note: “g t” means “greater than”.

Slicing Slicing means extracting values using a vector of indices >> B = A(3:5) % From 3 to 5, default increment is 1 ans = 7 1 3 >> odds = 1:2:length(A) ans = 1 3 5 >> A(odds) % odd values of A using predefined indices ans = 2 7 3 >> A(1:2:end) % odd values of A using anonymous indices ans = 2 7 3 >> small = A < 4; >> A(small) ans = 2 1 3 >> A(small) = A(small) + 10 What’s the result? What’s the result?

Useful Functions for Vectors All MATLAB functions accept vectors rather than single values and return a vector of the same length Special Functions: >> v = [1 2 3 4 5 6] >> sum(v) ans = 21 >> mean(v) ans = 3.5 >> min(v) ans = 1 >> max(v) ans = 6 >> [value where] = min(v) value = 1 where = 1

Example 1 Write a script to evaluate the function f(t) = 5 cos(10πt) – 2 cos(20πt – π/2) for t = -1.0 to 1.0 seconds in increments of 0.01 seconds. Solution: 1) Input/Output: input: values of t from -1.0 to 1.0 output : f(t) 2) Hand example: f(-1.0) = f(-0.99) = And so on..

Example 1(MATLAB script) Example 1 (Algorithm) Define t = -1.0 to 1.0 with increments of -0.01 Calculate f(t) = 5cos(10πt) – 2 cos(20πt – π/2) Display f(x) Example 1(MATLAB script) % Script to evaluate % f(t) = 5cos(10πt) – cos(20πt – π/2) % for t = -1.0 to 1.0 sec in increments of 0.01 % Author: Thomas Murphy t = -1.0:0.01:1.0; f = 5*cos(10*pi*t) - 2*cos(20*pi*t – pi/2);

Example 2 1) Write a script to evaluate the piecewise linear function 2) Input/Output: input: 3 ranges of t, 0 to 0.9, 1 to 2 and 2 to 4 output : f(t) 3) Hand example: f(0) = 0 f(0.1) = 0.2 And so on..

Example 2 (cont’d) 4) Algorithm: Define ranges of t (t1, t2 and t3) Calculate f(t1), f(t2) and f(t3) Concatenate the result Display result

Example 2 (cont’d) 5) MATLAB script % Script to evaluate the piecewise function f(t) % Author: Thomas Murphy % Date: July 20, 2006 %time regions for piecewise function t1 = 0.0 : 0.1 : 0.9; t2 = 1.0 : 0.1 : 1.9; t3 = 2.0 : 0.1 : 4.0; % evaluate piecewise function for the appropriate f1 = 2*t1; f2 = 4*t2 – 1; % regions f3 = 4 – 3*t3; t = [t1 t2 t3]; % concatenation of three results f = [f1 f2 f3];

Vector = 1-dimensional Array Row vector: v is an n × 1 array of values v1 to vn v = Column vector: w is a 1 x n array of values w1 to wn w =

A Matrix (multidimensional array) A matrix is an m x n array It has m rows and n columns Has m x n elements Is called an Array Matrix (1-d array is referred to as a vector) A(m x n) = a11 a12 … a1n a21 a22 … a2n . am1 am2 … amn

Creating an Array Matrix Entering the values directly A Semicolon identifies the next row >> v = [0,1,2,3,4,5,6] %create a 1 by 7 row matrix >> w = [0;1;2;3;4;5;6] %create a 7 by 1 column matrix >> A = [2, 5, 7; 1, 3, 42] %create a 2 by 3 matrix >> v1 = [1,2,3] >> v2 = [3,4,5] >> v3 = [6,7,8] >> B = [v1; v2; v3] Using the functions to create vectors filled with 0, 1, or random values between 0 and 1 zeros(rows, cols) Ones (rows, cols) Rand (rows, cols) >> B = zeros(2,5)%creates 2 by 5 matrix of zeros

Indexing an Array Matrix Syntax: A(row, col) returns the element(s) at the location(s) specified by the array row and column indices. A(row, col) = value replaces the elements at the location(s) specified by the array row and column indices. Examples: >> A = [0,1,2;3,4,5;6,7,8] >> A(1,1) >> A(2,3) >> A(2,:) >> A(2,3) = 2 >> A(2,:)=[1, 1, 1] %returns the (1,1) element = 0 %returns the (2,3) element = 5 %returns the second row %change element (2,3) to 2 %change row 2 to all 1s

Size & Dimensions of Array Matrix size() returns the dimensions of the matrix length() returns the larger of the dimensions (the larger number of the number of rows and columns) Example: >> E = [1:1:10; 11:1:20; 21:1:30] >> [nrows, ncol] = size(E)% size is a reserved word nrows =3 % nrows is a variable name (user defined) ncol = 10 % ncol is a variable name (user defined) >> length(E); ans = 10

Operating on an Array Matrix Four techniques extend directly from operations on vectors: Arithmetic operations Logical operations Applying library functions Slicing

Array Matrix Elt-by-elt Operations + - .* ./ .^ Between arrays of the same size or array and scalar Two arrays must be of the same size >> A = [3, 2, 1 ; 8, 7, 6]; >> B = [1, 2, 3 ; 4, 5, 6]; >> A + 2 ans = 5 4 3 10 9 8 >> A / 2 ans = 1.5 1 0.5 4 3.5 3 >> A.*B ans = 3 4 3 32 35 36 34 34

Array Matrix Logical Operations Are done on an element-by-element basis Result is an array of Boolean values, 0 and 1 >> A = [3, 2, 1 ; 8, 7, 6]; >> B = [1, 2, 3 ; 4, 5, 6]; >> A > = B ans = 1 1 0 1 1 1 >> A > = 5 0 0 0 1 1 1

Displaying a Table of Data % script to evaluate % f(t) = 5cos(10πt) – cos(20πt – π/2) % for t = -1.0 to 1.0 sec in increments of 0.01 % Author: Thomas Murphy t = -1.0:0.01:1.0; f = 5*cos(10*pi*t) - 2*cos(20*pi*t – pi/2); disp ([t f]); % disp is used to display any % text or array t = t’; f = f’; disp ([t’ f’]) % NOTE: Matlab uses the quote symbol ‘ to access the “fields of a structure” What are these?

disp Disp(‘t f’); Displays the label of a table Displ([t’ f’]); Displays the content

Example - Computing Soil Volume  Given: 1 - The depth of soil from a survey in the form of a rectangular array of soil depth. 2 - The footprint of the foundations of a building to be built on that site and the depth of the foundation.  Compute the volume of soil to be removed.

Survey Data

Building Footprint

Solution Script What units? clear clc % soil depth data by square, produced by survey depth = [8 8 9 8 8 8 8 8 7 8 7 7 7 7 8 8 8 7 8 8 8 8 8 8 8 7 7 7 7 7 8 7 8 8 8 7 . . . 9 8 8 7 7 8 7 7 7 7 8 8 9 9 9 8 7 8]; % estimated proportion of each square that should % be excavated area = [1 1 1 1 1 1 1 1 1 1 .3 0 0 0 0 0 0 0 0 0 0 0 0 0 .4 .8 .9 1 1 1 1 1 1 1 1 .6]; square_volume = depth .* area; total_soil = sum(sum(square_volume)) What units?

clear and clc The Matlab built-in function “clear” clear variables from memory.  Use the Matlab help to better understand what “clear” does clc clears the screen