Docsity

Arrays and Matrices: Indexing, Operations, Colon Notation, and Nested Loops, Slides of Computer Programming

Partial preview of the text

Download Arrays and Matrices: Indexing, Operations, Colon Notation, and Nested Loops and more Slides Computer Programming in PDF only on Docsity!

Arrays

Array

A variable to hold multiple values of the same type.

Example

x = [1, 2, 3, 4, 5, 6, 7]; y = ['a', 'b', 'c']; z = 'abc';

Arrays - Indexing

Indexing

Specifying an element of an array by providing its location.

Example

a = [2, 3, 5, 7, 11, 13]; a(1) % 2 a(2) % 3 a(3) % 5 a(6) % 13

s = 'Cornell' s(1) % 'C' s(4) % 'n'

Colon (:) Notation

Colon (:)

creates a sequence of numbers with constants steps

Example

% [1 2 3 4 5 6]

% [1 3 5]

% [6 4 2]

'a':'e' % 'abcde' 'e':2:'k' % 'egik'

Indexing with Colon

Parts of an array can be extracted by indexing with colon

notation.

Example

a = [2, 3, 5, 7, 11, 13]; a(1:2) % [2, 3] a(1:2:5) % [2, 5, 11] a(6:−3:1) % [13, 5] a(1:3:end) % [2, 7] a(2:end−1) % [3, 5, 7, 11]

Matrices - Comma vs. Semicolon

comma ,

seperates the columns

semicolon ;

seperates the rows

Example

a = [1, 2; 3, 4]; b = [1 2 3 4]; c = [1, 2, ... % ?? 3, 4]; d = [1; 2; 3; 4];

Matrices - Indexing

Indexing

Specifying an element of an array by providing its location.

Example

a = [ 1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12 ];

% variable(row index, column index) a(1,1) % 1 a(2,1) % 5 a(1,2) % 2 a(2,3) % 7 a(3,2) % 10

Matrices - Size, Some Generators

size

returns an array with the number rows and columns

ones(m,n), zeros(m,n)

generates all 1’s or all 0’s

rand(m,n)

generates random numbers between 0 and 1