CISC106-010, Fall 2007, Practice Questions                                    9/24/2007

 

Instructions: To get most out of this exercise, first try to solve the questions by yourself in the given order. Then, check your answers by clicking here.

 

(1) Assume you have a file named subtract.m in the current directory with the following content.

 

function result = subtract(x,y)

result = x-y;

 

What is printed to the screen when you type the following MABLAB statements in the MATLAB command prompt?

 

>> clear

>> a = 10;

>> b = 2;

>> subtract(a,b)

>> result

 

 

(2) Assume you have a file named subtract.m in the current directory with the following content.

 

result = x-y;

 

What is printed to the screen when you type the following MATLAB statements in the MATLAB command prompt?

 

>> clear

>> x = 10;

>> y = 2;

>> subtract

>> result

 

(3) Assume you have a file named subtract.m in the current directory with the following content.

 

function result = subtract(x,y)

result = x-y;

 

What is printed to the screen when you type the following MABLAB statements in the MATLAB command prompt?

 

>> clear

>> a = 10;

>> b = 2;

>> result = subtract(a,b);

>> result

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Answer 1:

 

>> result

??? Undefined function or variable 'result'.

 

 

This is the case because, result is a local variable to the function subtract and is not visible in the current workspace.

 

Answer 2:

 

>> result =

>>

>> 8

 

This is the case, because x and y are two variables defined in the current workspace. Entering the name of the script M-file (without the .m part), the script is executed and a value for the new variable result is calculated. Since subtract.m is a script M-file, new variable result is added into the current workspace after running the script subtract.

 

Answer 3:

 

>> result =

>>

>> 8

 

There are two variables named result in this question: (1) The output variable of the function subtract.  The output variable result is only visible inside the function subtract. (2) The other variable result is defined in the current workspace. The value returned by the function subtract is assigned as the value of the result in the current workspace.