100 likes | 195 Views
CS 170 – Intro to Scientific and engineering Programming . Looping through a 2D matrix. count = 0; for row = 1:5 for col = 1:5 if ( nums ( row,col ) ~= 0) count = count + 1; end end e nd OR count = sum(sum( nums ~= 0)). Count the peaks.
E N D
Looping through a 2D matrix count = 0; for row = 1:5 for col = 1:5 if (nums(row,col) ~= 0) count = count + 1; end end end OR count = sum(sum(nums ~= 0))
Count the peaks Write a program that prints each element of the array in the form: peaks(1,1) = 1 peaks(1,2) = 4, etc. • A peak is a value that islarger than its 4 neighbors CHALLENGE: Write a program that prints the peaks’ indexes:peak row = 2 peak column = 2
Logical arrays and indexing a = [12, 3, 45] b = logical([1, 0, 1]) a(b) What will this print? >> c = a(a>10) OR jj = 0; for ii = 1:length(x) if x(ii) > 10 jj= jj + 1; y(jj) = x(ii); end end
Logical indexing >> a(a>10) = 99 OR for ii = 1:length(a) if a(ii) > 10 a(ii) = 99; end end
Logical indexing [m,n] = size(M); for ii = 1:m for jj = 1:n if M(ii,jj) > 0.1 M(ii,jj) = sqrt(M(ii,jj)); end end end ~ M(M > 0.1) = sqrt(M(M > 0.1));
What about 2D arrays and logical indexing? >> A = [1 2 3; 4 5 6] A = 1 2 3 4 5 6 >> B = A(A>2) B = 4 5 3 6
Looping through vectorization • x = 1:1000: loops through the numbers 1, 2, …, 1000 and sets x(1) = 1, x(2)= 2, …, x(1000) = 1000 • A.*B loops through all the elements of A and B, and returns an array of the products of their elements (if A and B are not vectors, there will be nested loops) • A*B loops through the rows of A and the columns of B, forming an array of dot products (unless A and B are scalars, there will be nested loops)
Resources • “Introduction to Programming with Matlab”, J. Michael Fitzpatrick and John D. Crocetti • Lecture slides E77, Andy Packard, http://jagger.me.berkeley.edu/~pack/e77