CISC106-010, Fall 2007              11/7/2007

Practice Questions and Review for Midterm #2

Instructions: To get most out of this exercise first, do the questions yourself. Then click here to check your answers.

 

Outline

 

Strings, String Concatenation. 1

Review.. 2

Q1. 2

Q2. 2

Formatted Output with fprintf 2

Q1. 2

Q2. 2

Cell Arrays, Content indexing vs. Cell indexing. 3

Review – What is a Cell Array?. 3

Review – What is content indexing?. 4

Review – What is cell indexing?. 4

Review – Indexing in regular matrices. 4

Q1. 5

Q2. 5

Q3. 6

Q4. 6

Q5. 6

Q6. 6

Q7. 6

Q8. 6

Repetition Structures (while loops, for loops, nested loops) and Selection Structures (If/Else) . 6

Q1. 6

Q2. 6

Q3. 6

Q4. 7

Q5. 7

File Operations. 7

Review.. 7

Q1. 8

SPLITing a string using  regexp built-in function. 8

Q1. 8

Q2. 8

Script M-files, Function M-files, Test scripts. 8

Review.. 8

Chmod Unix Command. 8

Q1. 9

Q2. 9

 

Strings, String Concatenation

ReviewRemember that strings in MATLAB are regular vectors (i.e., 1xn matrices) of chars. For instance,

 

>> name = 'john'

 

name =

 

john

 

>> whos name

  Name      Size            Bytes  Class    Attributes

 

  name      1x4                 8  char     

        

i.e., name is a 1x4 matrix (i.e., a row vector) of char (That is all the elements of the matrix name is of type char).

 

Q1. Assume

 

>> name = ‘josh’;

 

Write a MATLAB expression to retrieve the character ‘s’ in the string name.

 

Q2. Assume

 

>> firstName = ‘mike’;

>> lastName = ‘brown’;

 

Write a MATLAB expression to create a MATLAB string fullName with value as below (note the space between mike and brown!)

 

>> fullName =

 

mike brown

Formatted Output with fprintf

Q1. What format specifier to use in the fprintf statement below,

 

>> fprintf('The answer is:_______\n', 12.34567)

 

so that exactly the following will be printed ( there are 4 spaces following the colon ).

 

>> The answer is:    12.35

 

Q2. Assume we have two variables name and age

 

>> name = ‘john’

>> age = 19

 

Complete the fprintf statement below (i.e., you need to fill in the four _______ parts using the variables and format specifiers)

 

>> fprintf('My name is _______ and I am _______ years old.\n', ______, ______)

 

so that it will print exactly the following.

 

>> My name is john and I am 19 years old

Cell Arrays, Content indexing vs. Cell indexing

Review – What is a Cell Array?: Like any other variables, a cell array is a matrix in MATLAB. But consider a cell array as a special type of matrix. Cell arrays are special in the sense that each element of a cell array is a matrix itself! While forming regular MATLAB matrices, we use brackets [], while forming cell arrays we use braces {}. Check out the examples below:

 

>> n = 1          

 

n =

 

     1

 

>> whos n

  Name      Size            Bytes  Class     Attributes

 

  n         1x1                 8  double             

 

>> A = [10 20 30; 40 50 60]

 

A =

 

    10    20    30

    40    50    60

 

>> whos A

  Name      Size            Bytes  Class     Attributes

 

  A         2x3                48  double             

 

>> C = {[10 20]; [true false]; 5}

 

C =

 

    [1x2 double ]

    [1x2 logical]

    [          5]

 

>> whos C

  Name      Size            Bytes  Class    Attributes

 

  C         3x1               206  cell   

 

Note that the scalar n is stored as a 1x1 matrix. A is a regular 2x3 matrix of type double (i.e., each element of the matrix A is a number). C is a 3x1 matrix of type cell (i.e., each element of the cell array C is a matrix!)  Note the following two points about the cell array C:

 

Ř      Even the scalar 5 in row 3 and column 1 of the cell array C is stored as a 1x1 matrix

Ř      Each element of the cell array C contains a matrix with a different dimension and different type of elements!

 

Now, you can appreciate how powerful it can be to use cell arrays in your MATLAB programming!        

 

Review – What is content indexing? : You access the elements of a cell array, using braces {}. Then you get the content of the matrix in the corresponding element of the cell array. E.g.:

 

>> C{1,1}

 

ans =

 

    10    20

 

>> whos ans

  Name      Size            Bytes  Class     Attributes

 

  ans       1x2                16  double             

 

C{1,1} returns the 1x2 matrix of doubles in the row 1 and column 1 of the cell array C.

 

Review – What is cell indexing?: If you use cell indexing with cell arrays, using regular parenthesis (), you get the matrices in the specified elements of the cell array all  wrapped in a cell array! That is cell indexing, returns a cell array. E.g.:

 

>> C(1,1)

 

ans =

 

    [1x2 double]

 

>> whos ans

  Name      Size            Bytes  Class    Attributes

 

  ans       1x1                76  cell              

 

C(1,1) returns a 1x1 cell array. The matrix in the cell array is the 1x2 matrix of doubles in the row 1, column 1 of the cell array C.

 

 

Review – Indexing in regular matrices: Note that, with regular matrices, you use regular parenthesis (), to retrieve the elements of the regular matrix. E.g.:

 

>> name = 'john'

 

name =

 

john

 

>> numbers = [10 20 30]

 

numbers =

 

    10    20    30

 

>> name(1,1)

 

ans =

 

j

 

>> numbers(3)

 

ans =

 

    30

 

 

For the questions in this section, assume the following MATLAB session below:

 

>> clear

 

>> A = [10 20 30]

 

A =

 

    10    20    30

 

>> B = [true false]

 

B =

 

     1     0

 

>> C = ['mike'; 'john']

 

C =

 

mike

john

 

>> mycell = {A B C} 

 

mycell =

 

    [1x3 double]    [1x2 logical]    [2x4 char]

 

Q1.  What is the type of

 

>> mycell{1,1}

 

a) 1x1 cell array or b)  1x3 matrix of doubles

 

Q2. What is the type of

 

>> mycell(1,3)

 

a) 1x1  cell array or b) 2x4 matrix of chars

 

Q3. What is the type of

 

>> mycell(1,:)

 

a) 1x3 cell array or b) 1x1 cell array

 

Q4. What is the output of

 

>> mycell{1,3}(1,2)

 

Q5. What is the output of

 

 >> mycell{1,3}(1,:)

 

Q6. What is the output of

 

>> mycell{3}

 

Q7. How to access char j of the string john in the cell array mycell? Write a MATLAB expression.

 

Q8. We want to convert string mike to string adam in the cell array mycell. Complete the expressions below:

 

>> mycell{1,3}(1, :) =

Repetition Structures (while loops, for loops, nested loops) and Selection Structures (If/Else)

Q1. Converting a for loop to a while loop: The code piece below prints the elements of a vector v on to the screen, all in one line. Write a while loop version of this code.

 

v = [10 20 30 40];

for index = [1: length(v)]

   fprintf('%d ', v(index));

end %for

fprintf('\n');

 

Q2. Converting a while loop to a for loop: The code piece below, prints numbers 1 thru’ 6 to the screen. Write a for loop version of this code.

 

i = 1;

while (i<=6)

   fprintf('%d ', i);

   i = i+1;

end % while

fprintf('\n');

 

Q3. Given a string, write a while loop (in a function M-file howManyMs.m) to return the number of character ‘m’  s in the string. The skeleton of howManyMs.m is given below. Fill in the rest of it.

 

Hint: You need to check every character of the string and see if it is ‘m’ or not.

 

function result = howManyMs(str)

%  inputs:

%     str: the string that we are searching the m's

%  outputs:

%     result: number of m's in the string

%  Example:

% >> howManyMs('how let the dogs out?')

%

% ans =

%   0

%

% >> howManyMs('I like M&M')          

%
% ans =

%     0

%

% >> howManyMs('I like m&m')

%

% ans =

%     2

 

 

 

return;

end % function

 

Q4. Write a for loop version of the function howManyMs.m in the Q1 above. Use the same function skeleton in Q3 to start writing your code.

 

Q5. Nested loops: What does the code piece below do? i.e., what is printed to the screen?

 

v = [10 20 30;

40 50 60;

70 80 90];

 

[rows cols] = size(v);

 

for c = [1:cols]

   for r = [1:rows]

      fprintf('%d ', v(r,c));

   end % of inner for loop

   fprintf('\n');

end % of outer for loop

File Operations

Review There are built-in MATLAB functions to open, read from, write into, and close the files that are lying in the unix file system (i.e., fopen, fgets, fgetl, fprintf, fclose – know how, why, and when to use these functions, look at Lab07).  

 

Q1. Assume we have a file named ‘input.txt’ in our current directory. input.txt includes lines of text. We want to copy (write) the first line of input.txt to another file named ‘output.txt’. The code piece to do this operation is below.

 

% open both files, one file to read the other one to write

fromFile = fopen('input.txt', 'r');

toFile  = fopen('output.txt', 'w');

 

% read one line from the input file

str = fgets(fromFile);

 

% write the line into the output file

fprintf(toFile, '%s', str);

 

% since you are done with the files, now close both files

fclose(fromFile);

fclose(toFile);

 

Modify the code above, to read all the lines from input.txt into output.txt.

 

Hint: Use a while loop. Read a line of input.txt and then write the line into output.txt. Repeat this process until you come to the end of the file input.txt (i.e., there is no line left to read).

SPLITing a string using  regexp built-in function

Q1. What is the type of the output of

 

>> regexp('my team is: galatasaray', ':' , 'split')

 

a) 1x2 matrix of char or b) 1x2 cell array

 

Q2. Assume

 

>> mystr = ‘eagles, 70000, 5 , 1’

 

Write a MATLAB expression to get 4 of the comma separated words in mystr.

Script M-files, Function M-files, Test scripts

Review See your labs, to review

-         How to convert a script M-file to a function M-file

-         Given a function, write a test script for the function

-         Given a test script, write the function for it

Chmod Unix Command

Assume that you are at the unix command prompt and you have the following files in your current directory

 

> ls -l

-rw-------   1 iaydin   2052         352 Nov  8 05:42 copyFromFile.m

-rw-------   1 iaydin   2052         100 Nov  8 03:23 forPrintVector.m

 

Q1. Write a Unix command to give write permission to group for the file copyFromFile.m.

 

Q2.  What does the following Unix command do?

 

> chmod g+rw copyFromFile.m