34
Fondamenti di Informatica Data abstraction: Vectors Prof. Emiliano Casalicchio http://www.ce.uniroma2.it/courses/FOI/

Data abstraction: Vectors

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Data abstraction: Vectors

Fondamenti di Informatica

Data abstraction: Vectors

Prof. Emiliano Casalicchio http://www.ce.uniroma2.it/courses/FOI/

Page 2: Data abstraction: Vectors

1-2

Objectives

This lecture discusses the basic calculations involving rectangular collections of numbers in the form of vectors. For this collections, you will learn how to:

■ Create them ■ Manipulate them ■ Access their elements ■ Perform mathematical and logical operations on

them

Page 3: Data abstraction: Vectors

1-3

Concept: Using Built-in Functions

n  In this chapter we will see the use of some of the functions built into MATLAB.

n  At the end of each chapter that uses built-in functions, you will find a summary table listing the function specifications.

n  For help on a specific function, you can type the following: >> help <function name>!

n  For example: >> 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.!

!

Page 4: Data abstraction: Vectors

1-4

Concept: Data Collections

This section considers two very common ways to group data: in arrays and in vectors. Data Abstraction allows us to refer to groups of data collectively:

  “all the temperature readings for May” or   “all the purchases from Wal-Mart.”

We can not only move these items around as a group, but also perform mathematical or logical operations on these groups, e.g.:

  compute the average, maximum, or minimum temperatures for a month A Homogeneous Collection is constrained to accept only items of the same data type – in this case, they will all be numbers

Page 5: Data abstraction: Vectors

1-5

MATLAB Vectors

Individual items in a vector are usually referred to as its elements. Vector elements have two separate and distinct attributes that make them unique in a specific vector:

  their numerical value and   their position in that vector.

For example, the individual number 66 is the third element in this vector. Its value is 66 and its index is 3. There may be other items in the vector with the value of 66, but no other item will be located in this vector at position 3.

Page 6: Data abstraction: Vectors

1-6

Vector Manipulation

We consider the following basic operations on vectors:

 Creating a Vector  Determining the size of a Vector  Extracting data from a vector by indexing  Shortening a Vector  Mathematical and logical operations on Vectors

Page 7: Data abstraction: Vectors

1-7

Creating a Vector – Constant Values

n  Entering the values directly, e.g. !!A = [2, 5, 7, 1, 3]

n  Automatically entering values e.g.

 as a range of numbers  as equally distributed in a linear space  as random, zeros, ones

Page 8: Data abstraction: Vectors

1-8

Creating a Vector – Entering the values as a range

B = [v1, v2, …, vn]={vi| vmin<=vi<=vmax,vi=vi-1+K, v1=vmin, i=2,..}!

dove k è un intero costante. Ad esempio K=3, vmin=1 e vmax=20 B=[1,4,7,10,13,16, 19]!

come fare? Proviamo a definire un algoritmo: 1.  leggi vmin, vmax e K 2.  i=1, vi=vmin

3.  i=i+1 4.  se vi-1+K > vmax allora termina 5.  altrimenti vi=vi-1+K 6.  vai a passo 3.

In the following lectures you will learn how to implement in Matlab

this algorithm…and more

Page 9: Data abstraction: Vectors

1-9

Creating a Vector – Entering the values as a range (2)

n  In Matlab B = {vi| vmin<=vi<=vmax,vi=vi-1+K, v1=vmin, i=2,..} =! = vmin:K:vmax! ad esempio B = 1:3:20! = [1,4,7,10,13,16, 19]!

1.  leggi vmin, vmax e K

2.  i=1, vi=vmin

3.  i=i+1

4.  se vi-1+K > vmax allora termina

5.  altrimenti vi=vi-1+K

6.  vai a passo 3.

Page 10: Data abstraction: Vectors

Homework: To design an algorithm that implements linspace

1-10

Creating a Vector – as equally distributed in a linear space

B = [v1, v2, …, vN]={N equally spaced points between Xmin and Xmax}!

ad esempio N=11, Xmin=0 e Xmax=20 B=[0 2 4 6 8 10 12 14 16 18 20]!

n  Matlab offers a built in function to do that C = linspace (Xmin, Xmax, N)!

Page 11: Data abstraction: Vectors

1-11

Creating a Vector - filled with 0, 1, random values

B = [v1, v2, …, vN];!!vi=0 for i=1,..,N!!vi=1 for i=1,..,N!!vi=xk where xk is a pseudorandom value uniformly or normally distributed !

All the cases can use the same algorithm!

1.  i=0; 2.  i=i+1; 3.  vi=x; 4.  if i=N then exit; 5.  go to 2;

x = 0 or 1 or Normal() or Uniform()

Page 12: Data abstraction: Vectors

1-12

Creating a Vector - filled with 0, 1, random values

Matlab offers built in function implementing the previous algorithm !%B = [v1, v2, …, vN];!B=zeros(1,n) %vi=0 for i=1,..,N !B=ones(1,n) %vi=1 for i=1,..,N!B=rand(1,n) %vi=xk where xk is a pseudorandom value ! !

%uniformly distributed !B=randn(1,n) %vi=xk where xk is a pseudorandom value ! !

%normally distributed !

Page 13: Data abstraction: Vectors

1-13

Size of Vectors and Arrays

Problem: we have a vector and we want to know the number of its elements MATLAB provides two functions to determine the size of arrays in general (a vector is an array with one row):

  the function size(A) when applied to the array A returns vector containing two quantities: the number of rows and the number of columns

 The function length(A) returns the maximum value in the size of an array; for a vector, this is its length.

Page 14: Data abstraction: Vectors

1-14

Indexing a Vector

n  The process of extracting values from a vector, or inserting values into a vector

n  Syntax:   v(index) returns the element(s)

at the location(s) specified by the vector index.

  v(index) = value replaces the elements at the location(s) specified by the vector index.

n  The indexing vector may contain either numerical or logical values

>> A=1:3:12!A =! 1 4 7 10!>> A(1)!ans =! 1!>> B=[2,4]!B =! 2 4!>> A(B)!ans =! 4 10!

indexing vector

Page 15: Data abstraction: Vectors

1-15

Numerical Indexing

n  The indexing vector may be of any length n  It should contain integer (non-fractional) numbers n  The values in the indexing vector are constrained by the following rules:

 For reading elements, all index values must be 1 <= element <= length(vector)

 For replacing elements, all index values must be 1 <= element

Page 16: Data abstraction: Vectors

1-16

Replacement Rules

1.  Either: •  All dimensions of the blocks on

either side of the replacement instruction must be equal, or

•  There must be a single element on the RHS of the replacement

2.  If you replace beyond the end of the existing vector, the vector length is automatically increased.

•  Any element not specifically replaced remains unchanged.

•  Elements beyond the existing length not replaced are set to 0.

>> A=1:3:12!A =! 1 4 7 10!>> B=[2,4];!>> A(B)=[0,0]!A =! 1 0 7 0!>> A(4)=99!A =! 1 0 7 99!>> A(7)=99!A =! 1 0 7 99 0 0 99!

Page 17: Data abstraction: Vectors

1-17

Logical Indexing

n  The indexing vector length must be less than or equal to the original vector length

n  It must contain logical values (true or false)

n  Access to the vector elements is by their relative position in the logical vector   When reading elements, only the

elements corresponding to true index values are returned

  When replacing elements, the elements corresponding to true index values are replaced

n  Beware – logical vectors in Matlab echo in the Command window as 1 or 0, but they are not the same thing.

>> a=true!a =! 1!>> a=false!a =! 0!>> 13>10!ans =! 1!>> mask=[true,false,true,true]!mask =! 1 0 1 1!>> A(mask)!ans =! 1 7 99!>> A(mask)=[66,66,66];!>> A!A =! 66 0 66 66!0 0 99!

Page 18: Data abstraction: Vectors

1-18

Shortening an Array

n  Never actually necessary. It is advisable to extract what you want by indexing rather than removing what you don’t want.

 Can lead to logic problems when changing the length of a vector

n  Accomplished by assigning the empty vector ([]) to elements of a vector, or to complete rows or columns of an array.

Page 19: Data abstraction: Vectors

1-19

Operating on Vectors

Three techniques extend directly from operations on scalar values:

■ Arithmetic operations ■ Logical operations ■ Applying library functions

Two techniques are unique to arrays in general, and to vectors in particular:

■ Concatenation ■ Slicing (generalized indexing)

Page 20: Data abstraction: Vectors

Operators precedence

n  Operator description and precedences http://www.mathworks.com/help/techdoc/matlab_prog/f0-40063.html

20

Page 21: Data abstraction: Vectors

1-21

Arithmetic operations

In the Command window, enter the following: >> A = [2 5 7 1 3];!>> A + 5!ans =!7 10 12 6 8!>> A .* 2!ans =!4 10 14 2 6!>> B = -1:1:3!B =!-1 0 1 2 3!

Page 22: Data abstraction: Vectors

1-22

Arithmetic operations (continued)

>> A .* B % element-by-element multiplication!ans =!-2 0 7 2 9!>> A * B % matrix multiplication!!!??? Error using ==> mtimes!Inner matrix dimensions must agree.!>> C = [1 2 3]!C =!1 2 3!>> A .* C % A and C must have the same length!??? Error using ==> times!Matrix dimensions must agree.!

!

Page 23: Data abstraction: Vectors

1-23

Logical operations

>> A = [2 5 7 1 3];!>> B = [0 6 5 3 2];!>> A >= 5!ans =!0 1 1 0 0!>> A >= B!ans =!1 0 1 0 1!>> C = [1 2 3]!>> A > C!??? Error using ==> gt!

Matrix dimensions must agree.

Page 24: Data abstraction: Vectors

Logical operators: NOT, AND, OR

24

AND, & OR, |

NOT, -

Truth tables

Page 25: Data abstraction: Vectors

1-25

Logical operations (continued)

>> A = [true true false false];!>> B = [true false true false];!>> A & B!ans =!1 0 0 0!>> A | B!ans =!1 1 1 0!>> C = [1 0 0]; % NOT a logical vector!>> A(C) % yes, you can index logical vectors, but ...!??? Subscript indices must either be real positive integers

or logicals.!

Page 26: Data abstraction: Vectors

1-26

A Footnote: the find function

n  Continuing the code above: >> C = find(B)!ans = ! [1 3]!

n  The find(...) function consumes a logical vector and returns the numerical indices of the elements of that vector that are true.

Page 27: Data abstraction: Vectors

1-27

Applying library functions

All MATLAB functions accept vectors of numbers rather than single values and return a vector of the same length. Special Functions: ■ sum(v) and mean(v) consume a vector and return a number ■ min(v) and max(v) return two quantities: the minimum or maximum value in a vector, plus the position in that vector where that value occurred. ■ round(v), ceil(v), floor(v), and fix(v) remove the fractional part of the numbers in a vector by conventional rounding, rounding up, rounding down, and rounding toward zero, respectively.

Page 28: Data abstraction: Vectors

1-28

Concatenation

n  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 may be any vector defined as a constant or variable, and the length of A will be the sum of the lengths of the individual vectors.   A = [1 2 3 42]!is a special case where all the component elements are scalar quantities.

Page 29: Data abstraction: Vectors

1-29

Slicing (generalized indexing)

n  A(4) actually creates an anonymous 1 × 1 index vector, 4, and then using it to extract the specified element from the array A.

n  In general, B(<rangeB>) = A(<rangeA>)!

where <rangeA> and <rangeB> are both index vectors, A is an existing array, and B can be an existing array, a new array, or absent altogether (giving B the name ans). The values in B at the indices in <rangeB> are assigned the values of A from <rangeA> .

Page 30: Data abstraction: Vectors

1-30

Rules for Slicing

■ Either the dimensions of <rangeB> must be equal to the dimensions of <rangeA> or <rangeA> must be of size 1

■ If B did not exist before this statement was implemented, it is zero filled where assignments were not explicitly made

■ If B did exist before this statement, the values not directly assigned in <rangeB> remain unchanged

Page 31: Data abstraction: Vectors

1-31

Representing Mathematical Vectors

n  An unfortunate clash of names n  Vectors in mathematics can be represented by Matlab

vectors   The first, second and third values being the x, y and z

components   Matlab vector addition and subtraction work as expected.   Matlab magnitude and scaling works as expected.   Dot product is just the sum of A .* B   Cross product has a Matlab function

Page 32: Data abstraction: Vectors

1-32

Engineering Example—Forces and Moments

n  So given a pair of forces A and B acting at a point P, find:

 The resultant force, and  The moment of that resultant

about the origin

Page 33: Data abstraction: Vectors

1-33

Vector Solution

clear!clc!PA = [0 1 1]!PB = [1 1 0]!P = [2 1 1]!M = [4 0 1]!% find the resultant of PA and PB!PC = PA + PB!% find the unit vector in the direction of PC!mag = sqrt(sum(PC.^2))!unit_vector = PC/mag!% find the moment of the force PC about M!% this is the cross product of MP and PC!MP = P - M!moment = cross( MP, PC )!!

Page 34: Data abstraction: Vectors

n  Homework

 exercise 3.1 – 3.10 of the book.

34