1 / 10

CS 170 – Intro to Scientific and engineering Programming

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.

dai
Download Presentation

CS 170 – Intro to Scientific and engineering Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 170 – Intro to Scientific and engineering Programming

  2. 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))

  3. 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

  4. 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

  5. Logical indexing >> a(a>10) = 99 OR for ii = 1:length(a) if a(ii) > 10 a(ii) = 99; end end

  6. 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));

  7. 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

  8. 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)

  9. Questions??

  10. 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

More Related