Docsity

Arrays and Array Operations in MATLAB: Lecture Notes, Slides of Computer Programming

Partial preview of the text

Download Arrays and Array Operations in MATLAB: Lecture Notes 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]

for - Examples

Example

% This will display values of x % at every iteration from 1 to 5 for x = 1: x end

for - Examples

Example

% Sum integers from 1 to 100 s = 0; for j = 1: s = s + j; end fprintf('1+..+100=%d\n',s);

More Nested

Example

while %

while %

end

end