Objective: To provide practice (or a refresher) with writingsimple MATLAB codes that employ common tools such as loops,functions, arrays, and MATLAB plotting tools.
P T 1: Functions and loops
The goal of this exercise is to plot the function
r(theta) = theta
where theta is a phase angle and r(theta) is the radius at thatangle, over the range - 3pi/2 =< theta =< 3pi/2 .
It is often useful to define a function to handle calculationsthat will be performed over and over again. Designing your codethis way presents several advantages:
•Individual functions that can build specific tasks can be builtand tested separately from the rest of the code. this not only canmake your program easy to debug, it breaks the programming tasksinto smaller more manageable chunks that can potentially be sharedamong multiple coders.
•Functions can be used by more than one program - so if you'vewritten a function that does something useful, you can reuse it ifyou need to perform the same task in another program.
We will write a simple program that plots the above functionusing a main program and a nction. In teams of two, decide whichperson will take the lead on the nction and which person will takethe lead on the main program.
The FUNCTION should take as input the phase angle theta andreturn as output the Cartesian (x,y) coordinates corresponding tothe point (theta,r(theta)) (defined as above). Recall that thefollowing functions can be used to convert polar coordinates toCartesian coordinates:
X = rcos(theta) y = rsin(theta)
For help with the syntax r nctions in MATLAB, type
help function
on the command line in MATLAB.
The MAIN PROGRAM should use a loop to pass phase anglesone-at-a-time to the function over the range of inputs, collect theoutputs, and then plot the results. For help with the syntax ofloops in MATLAB (and to help consider what kind of loop would beappropriate here), use the MATLAB help to and out more about thefollowing:
for if while
Part 2:
Passing arrays to functions
Repeat the above exercise,but instead of using a loop to passindividual values of theta to the function,the main program shoulddefine a vector of all values of theta that should be used, andpass the whole vector to the function. What needs to be changed inthe function, if anything, to accommodate this change? Once thesechanges are made, will the function still work when scalar valuesof are passed to it? (If not, try to make the necessary changes sothat the function will work for both scalar and vector inputs.)