1 Chapter 3 Arrays (2) 1. Array Referencing 2. Common Operations 1. Slicing 2. Diminution 3. Augmentation 3. List of Commonly Used Built-in Functions 1.

Slides:



Advertisements
Similar presentations
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Advertisements

Elementary Linear Algebra
4.3 Matrix Approach to Solving Linear Systems 1 Linear systems were solved using substitution and elimination in the two previous section. This section.
Introduction to Computing Science and Programming I
Section 2.3 Gauss-Jordan Method for General Systems of Equations
Review of Matrix Algebra
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
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.
C++ for Engineers and Scientists Third Edition
Matlab Intro. Outline Matlab introduction Matlab elements Types Variables Matrices.
Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
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.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Java Unit 9: Arrays Declaring and Processing Arrays.
1 1.1 © 2012 Pearson Education, Inc. Linear Equations in Linear Algebra SYSTEMS OF LINEAR EQUATIONS.
MATRICES AND DETERMINANTS
Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.
Matlab tutorial course Lesson 2: Arrays and data types
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
IE 212: Computational Methods for Industrial Engineering
1 Arrays 2.Common Operations 1. Slicing 2. Diminution 3. Augmentation 1.
ARRAY REFERENCING 1 1. II. Array Referencing Assume an array has values. It is useful to “refer to” the elements contained within it – as smaller portions.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Lists in Python.
Multi-Dimensional Arrays
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Copyright © 2014 Pearson Education, Inc. Publishing as Prentice Hall. 1 by Mary Anne Poatsy, Keith Mulbery, Lynn Hogan, Amy Rutledge, Cyndi Krebs, Eric.
Comp 249 Programming Methodology Chapter 10 – Recursion Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
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.
Array Addition  Two arrays can be added if and only if both arrays have exactly the same dimensions.  Assuming the dimension requirement is satisfied,
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.
Copyright © 2013, 2009, 2005 Pearson Education, Inc. 1 5 Systems and Matrices Copyright © 2013, 2009, 2005 Pearson Education, Inc.
Searching. RHS – SOC 2 Searching A magic trick: –Let a person secretly choose a random number between 1 and 1000 –Announce that you can guess the number.
Data Strcutures.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
TRAVERSING AN ARRAY My friend, the FOR loop Analyze an array in other ways than max,min,sort… 11.
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.
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.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
CSC 211 Data Structures Lecture 13
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.
(The Transpose Operator) 1 >> C=[ ; ; ] C = >> D=C' D =
Matlab tutorial course Lesson 4: Writing your own functions: programming constructs
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Chapter 1 Section 1.5 Matrix Operations. Matrices A matrix (despite the glamour of the movie) is a collection of numbers arranged in a rectangle or an.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Data Structures Arrays and Lists Part 2 More List Operations.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
Repetition Structures Chapter 9
Week 8 - Programming II Today – more features: Loop control
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
Matlab tutorial course
Loop Statements & Vectorizing Code
Matlab Intro.
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
CIS16 Application Development and Programming using Visual Basic.net
Loop Statements & Vectorizing Code
Matlab Intro.
Presentation transcript:

1 Chapter 3 Arrays (2) 1. Array Referencing 2. Common Operations 1. Slicing 2. Diminution 3. Augmentation 3. List of Commonly Used Built-in Functions 1. Applied to vectors 2. Applied to matrices 4. Traversing an Array 1

ARRAY REFERENCING Accessing the elements within the array 22

Array Referencing Once you have an array, we sometimes need to refer to the elements contained within it – as smaller portions of the array or even individually. Because our programs cannot know the values contained within the variable when we write it, we must refer to the positions of the elements as a more general means of accessing them. 3 ?… ?… 3 RD

Array Referencing, cont. We refer to the positions using “dimensions” – based upon how many dimensions make up a variable: A scalar has no dimensions – we simply refer to the variable itself. A vector has one dimension – either a number of rows or a number of columns. We use a single number to reference the values in a vector. A matrix has two or more dimensions. We use a number for EACH dimension: a row number, AND a column number (Typically - matrices with more dimensions would use another number for each additional dimension)

Array Referencing - Scalars x = 7; y = x + 5; We referenced the scalar x as the variable itself. 5

Array Referencing - Vectors Vectors use a single value. Each value is called an “index”: x = [5; -1; 4]; %original vector sum = 0; %start sum at zero sum = sum + x(1); %add first element sum = sum + x(2); %add second element sum = sum + x(3); %add third element Vectors have one dimension, so we use a single index in parentheses to specify which element we are using. Indexing starts at 1, and can go as high as how-many-elements-there-are. Yes, it seems quite repetitive… couldn’t we use a loop or something to make it easier? Hang in there… 6

Array Referencing - Matrices Matrices are similar. To access the 6 in this matrix: M = [1, 2, 3; 4, 5, 6; 7, 8, 9] we would say: M(2,3) It can directly be used in equations: x = 7 * M(2,3); %Result? _____ The row and column positions specified in the parentheses are referred to as “indices” (plural of “index”). We say that 2 is the “row index” and 3 is the “column index”. Row number always first! Column number always second! 7

Array Referencing, cont. But, we don’t have to use constants for the indices. We can also use variables: Instead of saying M(2,3), we can say: r=2; c=3; x = y + M(r, c); 8

Referencing - (Nested FOR Loops) “So what?”, you say. Well, with the power of loops it should become obvious. We can add up all of the values in a matrix, but only if we refer to each one: sum = 0; for r = 1:3 for c = 1:3 sum = sum + M(r, c); end The row index is gotten from a variable! The column index is gotten from a variable! 9

Referencing – Nested loops sum = 0; for r = 1:3 for c = 1:3 sum = sum + M(r, c); end Notice that the inner loop is changing its value while the outer loop waits. Only when the inner loop is complete does the outer loop increment. Why did we choose “r” and “c” for the loop variables? In this version, we move across all columns in a row before we proceed to the next row. Did we have to do this? If we choose to move down through all rows of a column before moving onto the next column, how would these loops change?

Referencing – (The range operator…) If you want to refer to “all” of a column or row, you can use the range operator by itself: V = M(:, 3); % from M, copy all rows in columns 3 to V 11 Note: The same could be done with columns! V = M(2, :); % Copy all columns of row 2 to V

ARRAY SLICING Used for: Accessing more than one element of an array Eliminating bad elements 12

Array Slicing In general, when we “pull out” part of an array, we call that a “slice”. The range operator is frequently used when getting a slice. % Pull out all elements in rows 1 and 2 % that are in columns 1 through 4 M1 = M(1:2, 1:4); 13

Real-life #1: Eliminating bad data In wind tunnels, the data is obtained throughout the tunnel. However, data is usually flawed around the walls, or far away form the object itself. Given an array of pressure/temperature/or density obtained, only the ones far from the wall are kept for analysis! 14

ARRAY DIMINUTION Making arrays smaller Deleting an element Deleting a row Deleting a column 15 Pronounce: “Dim’ – min – yoo’ – shun”

Array Diminution To eliminate the whole content, just re-define it as an empty-vector: scores = []; %delete all scores To eliminate a single value from a vector, you can either take a slice: HighScores = [757, 65, -13, -89]; HighScores = HighScores(1:3); %deletes last %score Or you can use the empty-vector: HighScores(4) = []; %removes 4 th score 16

Example Diminution After analyzing data, you may wish to get rid of some data: in this case, assign the empty brackets [] For example, get rid of the number 8 in b below: 17 This action changes the original vector and cannot be undone.

Array Diminution, cont. To eliminate an entire row/column: 1. Use the range operator, combined with 2. the empty-vector M = [1, 2, 3; 4, 5, 6]; M(:, 1) = [] … Read it as: QUESTION: Can we eliminate a single value from a matrix? M(2,2) = [] ? No – because that would mean some rows or columns would have more values than others. 18 %”M, all-rows, 1 st column, delete!”

Real life#2 – similar example 19 Clearly, bad results on the walls…

20 Real life#2 – similar example

21 Real life#2 – similar example

22 Real life#2 – similar example Suppose you want to delete the top now, since that is also a wall in the wind tunnel. What would be the command line? ____________________________________

AUGMENTING AN ARRAY 23

Array Augmentation, review Augmentation = “Adding to” = making an array bigger. For example: V = [1, 2, 3]; To augment more columns, it’s much like doing a running total or running product: to the current variable, perform an action: V = [V, 4, 5, 6]; To augment with another row vector variable: V1 = [3, 4, 5]; V2 = [6, 7, 8]; V1 = [V1; V2]; To augment with a column vector variable: V1 = [6; 8; 9]; V2 = [10; 20; 30]; V1 = [V1, V2]; Makes a matrix! Why did we use a comma? ________________ Result: _ [ _________________ ] _? Result: __ __ __. Result: __ __. __ 24

Array Augmentation, review Works for matrices, too: M1 = [1, 2, 3; 4, 5, 6]; %original matrix M1 = [M1; 7, 8, 9]; %add a row to M1 M1 = [M1, [11, 2, 33; 44, 33, 22; 1, 0, 2]] M1 = Be sure that you augment with the correct number of rows / columns! 25

Extending an array 26 Array b does not have 4 columns… mmm… what will it do?

27 Commonly Used Built-In Functions 27

Common Array Functions To create arrays2. To analyze arrays2. To loop through arrays zeros()max()length() ones()min()numel() rand()mean()size() sum() prod() sort()

1. TO CREATE ARRAYS No hardcoding Arrays useful and easy to create 29

Creating Special Arrays zeros() to create arrays with zeros e = zeros(nb of rows, nb of columns) ones() to create arrays with ones f = ones(nbRows, nbCols) rand() to create arrays with numbers between 0 and 1. g = rand(nbRows, nbCols) 30

Creating Special Arrays, cont. zeros() to create arrays with zeros e = zeros(one argument only) ones() to create arrays with ones f = ones(one argument only) rand() to create arrays with numbers between 0 and 1. g = rand(one argument only) 31 >> zeros(3) ans = >> ones(3) ans = >> rand(3) ans =

2. VECTOR ANALYSIS max(), min(), mean(), sum(), prod(), sort() 32

33 Example of using max() 2 different ways Note: max_of_b and where are arbitrary names. You could (but not should) pick blabla1 and blabla2 instead… HOWEVER: you must have two variables in THAT order: 1 st will represent the value, 2 nd will represent the position of the maximum This is the first time we’ve seen a function return multiple values. As you can see, the only change we made was that we decided that we wanted to save the second value instead of ignoring it Only collected a single return value Collecting two return values – but same function call!

3. MATRIX ANALYSIS max(),min(),mean(),sum(),prod(),sort() - huh? Again? Yes! 34

Library functions sum(), prod(), mean(), max(), min() have a different result than when applied to vectors vs. matrices By default, the operations are done on each column, thus giving the sum/product/average/max or min of each column. You can choose to apply the operation to any dimension, but you have to use the two-argument version: sum(x, 2) 1 = sum the elements in all rows (i.e. down the column) 2 = sum the elements in all columns (i.e. across the row) 3 = sum the elements in each row and column (i.e across “pages”) – 3Dimensional The result of these functions on an array is a vector. If you want the sum of a whole array, use sum(sum(arrayName)) 35

Using the sum() 36 The same rules apply for mean(), prod() NOT for min(), max(),

Sorting arrays There are two fundamental tasks when working with computer data: sorting and searching. You can build a PhD thesis out of efficiency of sorting and searching! Fortunately, we don’t have to – we’ll just use some MATLAB functions 37

Sorting Arrays, cont. Like sum(), max(), min(), etc., the sort() function works along the columns by default. But you can change that: >> a a = >> sort(a, 2, 'descend') ans = = sort all the columns in a row 2 This is the first time we’ve seen a non-numeric argument. Like numeric arguments, which non- numeric values are valid is determined by the function. Refer to the Help (F1 in MATLAB) for more info about each function. The sort() function has two possible values for the 3 rd argument: ‘ascend’ and ‘descend’. By default (if you don’t specify a third argument) the function sorts in ascending order.

Dimension of an array size() is a built-in function that returns a new vector with 2 values inside: the number of rows (first), the number of columns (second) length() is another built in function that returns the maximum value between the number of rows and columns of an array 39

TRAVERSING AN ARRAY My friend, the FOR loop Analyze an array in other ways than max,min,sort… 40

Linear Searching “Linear searching” is exactly how we typically work a search – we look at each element and see if it matches. We stop when we reach the end of the array. For example: Our program has generated a matrix. We would like to know if any value in the matrix exceeds the value of 10.

Linear Searching, cont. s = size(M); found = []; for r = 1:s(1) for c = 1:s(2) if M(r, c) > 10 found(1) = r; found(2) = c; end size() gives us # of rows and # of columns found will contain the position of the last value found that is greater than 10

Binary Searching Binary searching is a fancy name for how we use the phone book – an extremely fast way to search. Since names are sorted in the phone book, we can skip massive portions. For example, if the last name starts with “T”, we can skip about 75% of the phonebook!

Binary Searching, cont. Just like with the phonebook, we can search arrays using binary searching. And like the phonebook, this method requires that the information already is sorted. Although it can be modified for matrices, it is most useful when searching vectors.

Binary Searching, cont. To use binary searching: Sort the vector Repeat until found or run out of values to check Compute the ½ way index for the current range Is it what you want? If not, is it too high or too low? If too high, move to middle of lower range If too low, move to middle of upper range

Binary Searching, cont. clear clc % Give us some values v = floor(25*rand(1, 10)) % Search for the value 10 value = 10; % Sort the data v = sort(v) % Setup the vars hi = 10; lo = 1; done = false; found = false; while (~done && ~found) range = hi - lo + 1; index = floor(range / 2) + lo; if (v(index) == value) found = true; elseif (v(index) > value) hi = index-1; else lo = index+1; end if hi<lo done = true; end Repeat until found or run out of values to check Compute the ½ way index for the current range Is it what you want? If too high, move to middle of lower range If too low, move to middle of upper range Have we used up all the values?