Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Arrays and Vectors

Similar presentations


Presentation on theme: "Chapter 3 Arrays and Vectors"— Presentation transcript:

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

2

3 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

4 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.

5 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

6 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

7 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

8 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 =  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

9 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

10 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 = 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 = Ending number Starting number Increment 1-10

11 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

12 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 x 5 8 2 9 5 11 21 8

13 Add and Remove To add more than one element, create a new vector by concatenating elements >> x = [vecDirect 12, 14] x = 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 x 5 8 2 9 5 12 14

14 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

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

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

17 Multiplication … and Multiplication
Mathematics Matlab

18 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 = [ ]; >> A + 5 ans = >> A .* 3 % elt-by-elt multiplication >> B = -1:1:3 B =

19 >> 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 = [ ]; %B = >> A .* B % Elt-by-Elt multiplication ans = >> 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.

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

21 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 = >> A(odds) % odd values of A using predefined indices ans = >> A(1:2:end) % odd values of A using anonymous indices ans = >> small = A < 4; >> A(small) ans = >> A(small) = A(small) + 10 What’s the result? What’s the result?

22 Useful Functions for Vectors
All MATLAB functions accept vectors rather than single values and return a vector of the same length Special Functions: >> v = [ ] >> 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

23 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..

24 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);

25 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..

26 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

27 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];

28 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 =

29 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) = a a … a1n a21 a22 … a2n . am1 am2 … amn

30 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

31 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

32 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

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

34 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 = >> A.*B ans = 3 4 3 34 34

35 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 = >> A > = 5

36 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?

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

38 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.

39 Survey Data

40 Building Footprint

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

42 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


Download ppt "Chapter 3 Arrays and Vectors"

Similar presentations


Ads by Google