CS 1132 lab exercise 1

When you have completed the exercise, submit your responses on Gradescope (accessible from our Canvas site). If you do not finish this exercise during class, you have until Wednesday, September 8, at 2:30pm (before next week’s lab) to submit it.

If you have any questions, ask your lab instructor or a consultant immediately! They are in the lab to help you learn the material.

MATLAB built-in functions

MATLAB provides numerous built-in variables and functions. For each line below, type the text in the Command Window and press <Enter> to see what happens. Is the result what you expect? Fill in the blanks below with the screen output for that line.

% This is a comment--no action is executed by the computer
% From this point on, read but do not type the text after the % symbol in a line.

% Variables, constants, and simple calculations:
a= 100  % Look at the Workspace Pane: a VARIABLE called a has been created
a= 101  % Look at the variable’s value in the Workspace Pane
b= 99
a/b                        % _____________________________
ans
y= ans                     % _____________________________
x = 2;
y = x^x; z = y^y           % _____________________________

% Built-in functions:
sqrt(x)
pi  % a built-in variable
cos(pi)                    % _____________________________
abs(ans)
abs(cos(pi))               % _____________________________
exp(ans)
mod(7,2)                   % _____________________________ Function rem is similar
help mod  % quick function reference
help rem
doc rem   % detailed function documentation

b= (4*2) ...
+ 1           % What does ... do? _____________________________
              % It’s called the ellipsis

Running and editing a MATLAB program

Set up your flash drive (or cloud storage or other storage device) to organize all the files that you will write in the course. See the announcement “file storage” on the course website for more info.

From the course website (http://www.cs.cornell.edu/courses/cs1132), download the file convertCel2Fah.m (see Lab 1 in the Schedule & Files table) to the folder that you will use for storing your Exercise 1 files, e.g., cs1132/exercise/ex1/. The easiest way is to right-click on the file name, select save link as… , and browse to your folder. Make sure that the file name remains convertCel2Fah.m without any space and parentheses. If your machine has added any extra characters to the file name, e.g., convertCel2Fah (1).m , after saving the file you must change the name to be without any space and parentheses before you open/run the file in MATLAB.

Now set the Current Directory to be the directory in which you have stored your file convertCel2Fah.m. You should now see the file listed in the Current Directory Pane.

To run the script convertCel2Fah.m, in the Command Window type the file name without the extension .m.

To read the program, open the program file in the Editor Window: select menu options File→Open and then select or type the file name convertCel2Fah.m. (Or in the Current Directory Pane double click on the file name.)

Observe that the descriptive output was printed using the built-in function fprintf(), which allows you to print the value of a variable as text. Now change the presentation of the result by modifying the last statement in the program:

  1. Change the substitution sequence from %.3f to %.8f. The substitution sequence is also called the format sequence. Save and run the program again and notice that the format the number printed has changed. What does the substitution sequence %.8f specify?

  2. Say, you want to use 10 character spaces for printing the entire value (including the decimal point) with 2 decimal places shown. You will then use the substitution sequence %10.2f. Again, make this change and observe the print format.

Now save the file as convertFah2Cel.m and then modify it to prompt the user for a temperature in degrees Fahrenheit and convert and print the temperature in Celsius. Modify the fprintf() statement to print the result to one decimal place. Test your program a few times using different input values. (You can check the answers using a search engine.)

User-defined function

  1. Implement a function xSquared() that returns the square of a number. Which is correct?

    1. function out = xSquared(x)
      % out is the square of x; x is a number.
      x = input('Type any real number: ');
      out = x*x;
      
    2. function out = xSquared(x)
      % out is the square of x; x is a number.
      out = x*x;
      
  2. Implement a function xSquared() that returns the square of a number. Which is correct?

    1. function out = xSquared(x)
      % out is the square of x; x is a number.
      out = x*x;
      fprintf('The square of x is %.4f \n', out)
      
    2. function out = xSquared(x)
      % out is the square of x; x is a number.
      out = x*x;
      
  3. Implement a function xToTheN(x,n) that returns the nth power of a number. Which is correct?

    1. function y = xToTheN(x,n)
      % y is x^n where x and n are each a number.
      y = x^n;
      
    2. function y = xToTheN(x)
      % y is x^n where x and n are each a number.
      n = input(’Enter a positive number: ’);
      y = x^n;
      
  4. Given the correct function xToTheN() from above, which script(s) below correctly compute(s) the nth power of a number and add(s) 2 to the result?

    1. y + 2
    2. z = xToTheN(3,5); z = z + 2
    3. a = 1; b = 2; z = xToTheN(a,b) + 2
    4. function y = xToTheN(3,5); y = y + 2
    5. z = xToTheN(3,5) + 2

for-loop

A for-loop repeats the loop body—the statements between the loop header and the end keyword—a pre-determined number of times. (The loop header is the line that begins with the keyword for). What does each loop below do? Write in each blank the output from executing the loop above.

for a = 2:1:6
    disp(a)        % ___________________________________
end

for b = 2:6
    disp(b)        % ___________________________________
end

for c = 12:0.5:14
    disp(c)        % ___________________________________
end

for d = 0:-2:-6
    disp(d)        % ___________________________________
end

for f = 0:-2:-7
    disp(f)        % ___________________________________
end

for g = 5:2:1
    disp(g)        % How many times does the loop body execute? ________
end                % Any error message? ________

CMS

You will use CMS to submit homework and view your scores and grading comments. If you preenrolled in CS 1132, you can use CMS already. Try to log on CMS now. If CS 1132 is not listed as one of your courses, ask your lab instructor to add you to CMS. Note that your programming assignments must be submitted through CMS.

[Bonus] Different ways to create vectors (1-dimensional arrays)

In the scripts convertCel2Fah and convertFah2Cel we used scalar variables. A scalar variable stores one value at any moment in time. Now we look at the array variable, which stores a list of values. One-dimensional arrays (a list extending in one direction) are also called “vectors.”

This section is in preparation for one of Friday’s topics; your responses do not need to be submitted.

a= zeros(1,3)  %________________

b= ones(3,1)   %________________  What do the arguments specify?______________________

c= rand(1,4)   %________________

d= 10:2:17     %________________

f= 10:-1:7     %________________

g= 10:2:0      %________________

h= [10 20 40]  %________________  What does the space separator do?___________________

m= [10,20,40]  %________________  What does the comma separator do?___________________

n= [10;20;40]  %________________  What does the semi-colon separator do?______________

p= [a h]       %________________

q= [b; n]      %________________

r= [a n]       % ERROR--mismatched dimensions! (Attempt to concatenate a column to
               % a row)

s= b'          %________________  This operation is called "transpose"

t= [a b']      %________________

u= sum(t)      %________________  What does function sum do?__________________________