Lab 3

This lab will be mostly focused on constructing loops inside of loops

Contents

Exercise 1: Summing matrix entries

The commands

n = 10;
A = rand(n);

generate an $n \times n$ matrix with randomly chosen elements. This is an easy way to generate a matrix to test an algorithm. Write code to generate A and then loop through all its elements to sum all the elements. Let a variable

SUM

be the total sum of all the entries. For $n = 50,100,150,\ldots$ plot

SUM/(n^2/2)

against $n$. What do you notice?

Exercise 2: Vectorizing

MATLAB® is much more efficient when you add two vectors instead of adding a large number of scalars. Thisiis sometimes called vectorizing: allowing your code to run purely with vector operations. For example,

A(1,:) + A(2,:)

will add the first two rows of $A$. Perform the same steps as in the previous exercise by

Use the

tic/toc

commands to examine the speed difference.

Exercise 3: Triangular matrices

Define the matrix $A$ as in Exercise 1. Write code that zeros out entries to make $A$ an upper-triangular matrix. Do the same to make $A$ a lower-triangular matrix.