1 / 8

COMP 116: Introduction to Scientific Programming

COMP 116: Introduction to Scientific Programming . Lecture 18: Functions lab. Function examples. Creating a function. Using a function. Exercise 1. Write a function “ plot_a_square ” that given a center c and edgelength e plots a square of edgelength e centered at c

molly
Télécharger la présentation

COMP 116: Introduction to Scientific 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. COMP 116: Introduction to Scientific Programming Lecture 18: Functions lab

  2. Function examples Creating a function Using a function

  3. Exercise 1 • Write a function “plot_a_square” that • given a center c and edgelengthe • plots a square of edgelengthe centered at c • Write a function “in_a_square” that • given a point p,center c and edgelengthe • Returns true if p is inside the square and false otherwise

  4. The counted loop solution: for loops forvar= vector commands end Keywords • Read this as: • Run commands as many times as there are entries in vector • Each time, assign var to be equal to one of the entries

  5. A=[2 8 3 12]; fori=1:length(A) A(i)=A(i)+1; disp(A(i)); end A=[2 8 3 12]; A(1)=A(1)+1; disp(A(1)); A(2)=A(2)+1; disp(A(2)); A(3)=A(3)+1; disp(A(3)); A(4)=A(4)+1; disp(A(4)); Output: 3 9 4 13

  6. What does this code do % Assume A is a preassigned vector var=0; fori=1:length(A) var=var+A(i); end

  7. Exercise II • Write a script that uses “plot_a_square” • in a for loop • to plot 20 squares with random edgelengths and random centers • You will need hold on • Add a while loop to the above script. In the loop, • Allows user to click on the figure window. (Use ginputto get the coordinates of the click) • Use “in_a_square” to check which squares the click lies in. (You will need a for loop here). Display the centers of the squares that have been clicked.

  8. Assignment 2 • plot returns a handle that can be used to modify the figure later. • >>h=plot(x,y); % h is the handle here. • >>set(h, ’Color’, ’r’); % changes the color to red • Modify plot_a_square function to return the handle • Modify the script from exercise II so that • you store the handles in an array • If the clicked point lies in an array change the color of the corresponding square to red

More Related