CS 1132 lab exercise 3

You have until Wednesday, September 22, at 2:30pm (before next week’s lab) to complete this exercise on Matlab Grader.

Subarray

Type each of the following expressions in the Matlab Command Window (and press Enter) to see what it does. Write the screen output on each blank.

A= [9 8 7 2 0]

b= A(3)

C= A(3:5)           % _________________________________

D= [A; ...
    ones(1,5); ...
    4*ones(1,5)]    % _________________________________

E= D(1:3,2:4)       % _________________________________

F= D(:,2)           % _________________________________
% What does the colon mean when it is used where indices are expected?

% Ask for help now if you are unsure how to access a subarray

Find a value in a matrix

Write the following function:

function [rs, cs] = findInMatrix(n,M)
% Find all occurrences of the value n in matrix M.
% rs and cs are column vectors of row and column numbers such that 
%   M(rs(k),cs(k)) is equal to n.
% If n is not found in M, rs and cs are empty vectors.

Example: Given matrix D from Question 1 above, the function call [rows, cols]= findInMatrix(4,D) should return in rows the vector [3; 3; 3; 3; 3] and in cols the vector [1; 2; 3; 4; 5].

Use loop(s). The purpose of this lab exercise is to practice with loops and matrices, therefore do not use any built-in functions other than size(). For extra practice, first hand-write the solution without using the computer. Then type up your function in Matlab for testing.

Cumulative sums

Write the following function:

function A = matrixCSums(M)
% M is a numeric matrix and A has the same size as M.
% Each element in A is the sum of the corresponding element in M and all
% the elements above it.  Example:
%   M = [ 1 3; ...             A = [ 1  3; ...
%         4 5; ...     then          5  8; ...
%        -7 2]                      -2 10]

Be sure to log off the lab computer before leaving the lab.