80 likes | 142 Views
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
E N D
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 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
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
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
What does this code do % Assume A is a preassigned vector var=0; fori=1:length(A) var=var+A(i); end
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.
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