120 likes | 201 Views
COMP 116: Introduction to Scientific Programming . Lecture 3: Arrays and Matrices. Recap. Array(vector ) variable y Creating arrays >> x=[5 3 2 11 6 5 2 ] >> x= 7:10 x= >> x=rand(1,8). Array operations. x =[5 3 7 ],y=[1 2 3] Array scalar operations >>x+2 ans =[7 5 9]
E N D
COMP 116: Introduction to Scientific Programming Lecture 3: Arrays and Matrices
Recap • Array(vector) variable y • Creating arrays >> x=[5 3 2 11 6 5 2] >> x= 7:10 x= >> x=rand(1,8)
Array operations x=[5 3 7],y=[1 2 3] Array scalar operations >>x+2 ans=[7 5 9] >>x*2 Array vector operations (Both arrays are of same length) >>x+y >>x.*y (Use . for multiplication and division) ans=[5 6 21] Plotting (Both arrays are of same length) >>plot(x,y)
For today • Arrays • Indexing • Matrices • Creating • Images
Indexing arrays • x=[3 6 9 12 15 18] • x(i) gives you the ith element of the array >>x(2) >>x(3)=7 >>x(8) • x(end) the last element >>x(end) • x(i:j) array of elements in {i,i+1,i+2,…,j} positions >>x(3:5) • x([i j k l]) gives you the array [x(i) x(j) x(k) x(l)] >>x([5 2 1])
Exercise • Create the array [3 4 5 6 7] using the colon operator and assign it to variable x >>x=3:7 • Modify this array to the array [3 9 10 11 7] >>x(2:4)=9:11
For today • Arrays • Indexing • Matrices • Creating • Images
Matrices • Each element of the matrix is a variable(memory location) • To create this 3x4 matrix • y=[3 4 8 41; 35 7 22 11; 8 11 27 2] • An array is a 1xn matrix
Matrix operations • m=[3 6 4; 1 2 3] • Matrix-Scalar operations >>m=m*2 >>n=m-3 • Matrix-matrix operations (must be same size) >>p=m+n >>q=m.*n (use . for multiplication and division)
Creating matrices >>rand(m,n) mxn matrix of random numbers >>zeros(m,n) all zeros >>ones(m,n) all ones >>eye(m,n) identity matrix >>diag(v) diagonal matrix >>doc <command_name> to get detailed documentation e.g. >>doc diag
For today • Arrays • Indexing • Matrices • Creating • Images
Images • Images are matrices where each element of the matrix corresponds to the intensity at the corresponding pixel >>im_matrix=imread(‘picture.jpg’) reads the file picture.jpg into the matrix im_matrix • doc imread for more information >>imagesc(im_matrix) displays the image corresponding to im_matrix