KEMBAR78
Chapter 5: Vectorized Code Exercises | PDF | Matrix (Mathematics) | Function (Mathematics)
0% found this document useful (0 votes)
360 views8 pages

Chapter 5: Vectorized Code Exercises

This document contains 17 exercises related to vectorizing code in MATLAB. The exercises cover topics like: 1) Rewriting for/while loops using vectorized code with single statements 2) Using built-in functions like sum(), cumsum(), cumprod() to perform vector operations 3) Working with matrices and vectors to find max/min values, perform element-wise operations, and more. 4) Writing functions to operate on vectors and matrices in a vectorized manner.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
360 views8 pages

Chapter 5: Vectorized Code Exercises

This document contains 17 exercises related to vectorizing code in MATLAB. The exercises cover topics like: 1) Rewriting for/while loops using vectorized code with single statements 2) Using built-in functions like sum(), cumsum(), cumprod() to perform vector operations 3) Working with matrices and vectors to find max/min values, perform element-wise operations, and more. 4) Writing functions to operate on vectors and matrices in a vectorized manner.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter 5: Vectorized Code

 
Exercises 
 
1) The following code was written by somebody who does not know how to use 
MATLAB efficiently.  Rewrite this as a single statement that will accomplish exactly 
the same thing for a matrix variable mat (e.g., vectorize this code): 

[r c] = size(mat);
for i = 1:r
for j = 1:c
mat(i,j) = mat(i,j) * 2;
end
end
 
>> mat = mat * 2
 
2) Vectorize this code!  Write one assignment statement that will accomplish exactly 
the same thing as the given code (assume that the variable vec has been initialized): 
 
result = 0;
for i = 1:length(vec)
result = result + vec(i);
end

>> result = sum(vec)


 
3) Vectorize this code!  Write one assignment statement that will accomplish exactly 
the same thing as the given code (assume that the variable vec has been initialized): 
 
newv = zeros(size(vec));
myprod = 1;
for i = 1:length(vec)
myprod = myprod * vec(i);
newv(i) = myprod;
end
newv % Note: this is just to display the value

>> newv = cumprod(vec)


 
4) Create a 1 x 6 vector of random integers, each in the range from 1 to 20.  Use 
built‐in functions to find the minimum and maximum values in the vector.  Also 
create a vector of cumulative sums using cumsum. 
 
Ch5Ex4.m 
% Create a random vector and use built-in functions
% to find the minimum, maximum, and cumulative sums

vec = randi([1,20], 1,6)


min(vec)
max(vec)
cvec = cumsum(vec)
 
5) Write a relational expression for a vector variable that will verify that the last 
value in a vector created by cumsum is the same as the result returned by sum. 
 
>> vec = 2:3:17
vec =
2 5 8 11 14 17
>> cv = cumsum(vec)
cv =
2 7 15 26 40 57
>> sum(vec) == cv(end)
ans =
1
 
6) Create a vector of five random integers, each in the range from ‐10 to 10.  
Perform each of the following using only vectorized code: 
 
>> vec = randi([-10, 10], 1,5)
 
 subtract 3 from each element 
 
>> vec-3
 
 count how many are positive 
 
>> sum(vec > 0)
 
 get the absolute value of each element 
 
>> abs(vec)
 
 find the maximum 
 
>> max(vec)
 
7) Create a 3 x 5 matrix.  Perform each of the following using only vectorized code: 
 
>> mat = randi([-10 10], 3,5)
 
 Find the maximum value in each column. 
 
>> max(mat)
 
 Find the maximum value in each row. 
 
>> max(mat, [], 2)
>> max(mat')
 
 Find the maximum value in the entire matrix. 
 
>> max(max(mat))
 
8) Write a function called geomser which will receive values of r and n, and will 
calculate and return the sum of the geometric series: 
1 + r + r2 + r3 + r4 + ... + rn
The following examples of calls to this function illustrate what the result should be: 
>> geomser(1,5)
ans =
6

>> disp(geomser(2,4))
31
 
geomser.m 
function sgs = geomser(r, n)
% calculates the sum of the geometric series
% 1 + r + r^2 + r^3 + ... r^n
% Format of call: geomser(r, n)
% Returns sum of the series

v = 0:n;

terms = r .^ v;

sgs = sum(terms);
end
 
9) Generate a random integer n, create a vector of the integers 1 through n in steps 
of 2, square them, and plot the squares. 
 
Ch5Ex9.m 
% Create a vector of integers 1:2:n where n is random
% square them and plot the squares

n = randi([1,50])
vec = 1:2:n;
vecsq = vec .^ 2;
plot(vecsq,'k*')
title('Squares of integers')
 
10) A vector v stores for several employees of the Green Fuel Cells Corporation their 
hours worked one week followed for each by the hourly pay rate.  For example, if 
the variable stores 
>> v
v =
33.0000 10.5000 40.0000 18.0000 20.0000 7.5000
that means the first employee worked 33 hours at $10.50 per hour, the second 
worked 40 hours at $18 an hour, and so on.  Write code that will separate this into 
two vectors, one that stores the hours worked and another that stores the hourly 
rates.  Then, use the array multiplication operator to create a vector, storing in the 
new vector the total pay for every employee. 
 
>> hours = v(1:2:length(v))
hours =
33 40 20

>> payrate = v(2:2:length(v))


payrate =
10.5000 18.0000 7.5000

>> totpay = hours .* payrate


totpay =
346.5000 720.0000 150.0000
 
11) Write a function repvec that receives a vector and the number of times each 
element is to be duplicated. The function should then return the resulting vector. Do 
this problem using built‐in functions only. Here are some examples of calling the 
function: 
 
>> repvec(5:-1:1,2)
ans =
5 5 4 4 3 3 2 2 1 1

>> repvec([0 1 0],3)


ans =
0 0 0 1 1 1 0 0 0

repvec.m
function outvec = repvec(vec,n)
% Duplicates every number in a vector n times
% Format of call: repvec(vector, n)
% Returns a new vector
mat = repmat(vec,n,1);
outvec = reshape(mat,1,n*length(vec));
end

12) The mathematician Euler proved the following: 
2 1 1 1
1     
6 4 9 16
 
Rather than finding a mathematical proof for this, try to verify whether the 
conjecture seems to be true or not.  Note: there are two basic ways to approach this: 
either choose a number of terms to add, or loop until the sum is close to 2/6. 
 
Ch5Ex12.m 
% Test Euler's theory that pi^2/6 = 1 + 1/4 + 1/9 + ...

fprintf('pi^2/6 is %.2f\n', pi^2/6)

% Try 25 terms
n = 25;
i = 1:n;
seriessum = sum(1./i.^2);
fprintf('The sum of %d terms is %.2f\n',n,seriessum)
 
When working with images, it is often necessary to “crop” one image to match the size 
of another.  Images are represented very simply in MATLAB as matrices of numbers.  
However, these matrices are quite large.  Depending on the resolution, the number of 
rows and columns could easily be in the thousands.  It is therefore extremely important 
when working with image matrices to vectorize the code. 
 
 13) Write a script that will read from a file oldfile.dat into a matrix.  It will create a 
square matrix (same number of rows and columns) by deleting rows or columns as 
necessary, and then write this new square matrix to a new file called squarefile.dat.   
For example, if the original matrix is 4 x 6, the new matrix would be created by 
deleting the fifth and sixth columns to result in a 4 x 4 matrix.  Another example: if 
the original matrix is 3 x 2, the third row would be deleted to result in a 2 x 2 matrix.  
The script should be general and work regardless of the size of the original file and 
should not use any loops or if statements.  Create the data file first. 
 
Ch5Ex13.m 
% Reads a matrix from a file, creates a square matrix
% from it by deleting rows or columns as necessary and
% writes the resulting matrix to a new file

load oldfile.dat
mat = oldfile;

s = sort(size(mat));

newm = mat(1:s(1), 1:s(1));

save squarefile.dat newm -ascii


 
14) A file called “hightemp.dat” was created some time ago which stores, on every 
line, a year followed by the high temperature at a specific site for each month of that 
year.  For example, the file might look like this: 
89    42  49  55  72  63  68  77  82  76  67 
90    45  50  56  59  62  68  75  77  75  66 
91    44  43  60  60  60  65  69  74  70  70 
etc. 
 
As can be seen, only two digits were used for the year (which was common in the 
last century).  Write a script that will read this file into a matrix, create a new matrix 
which stores the years correctly as 19xx, and then write this to a new file called 
“y2ktemp.dat”.  (Hint: add 1900 to the entire first column of the matrix.)  Such a file, 
for example, would look like this: 
1989  42  49  55  72  63  68  77  82  76  67 
1990  45  50  56  59  62  68  75  77  75  66 
1991  44  43  60  60  60  65  69  74  70  70 
etc. 
 
Ch5Ex14.m 
% Solve the Y2K problem!

load hightemp.dat

newmat = hightemp;
newmat(:,1) = newmat(:,1) + 1900;

save y2ktemp.dat newmat -ascii


 
15) Write a script that will prompt the user for a quiz grade and error‐check until 
the user enters a valid quiz grade.  The script will then echo print the grade.  For this 
case, valid grades are in the range from 0 to 10 in steps of 0.5.  Do this by creating a 
vector of valid grades and then use any or all in the condition in the while loop. 
 
Ch5Ex15.m 
% Prompt the user for a quiz grade and error-check
% until a valid grade is entered; using any or all

quiz = input('Enter a quiz grade: ');


validgrades = 0: 0.5: 10;

while ~any(quiz == validgrades)


quiz = input('Invalid! Enter a quiz grade: ');
end

fprintf('The grade is %.1f\n', quiz)


 
16) Which is faster: using  false or using logical(0) to preallocate a matrix to all 
logical zeros?  Write a script to test this. 
 
% Test to see whether logical(0) or false is faster

fprintf('Start with logical(0)\n\n')


tic
mat(1:100, 1:100) = logical(0);
toc

fprintf('Now for false \n\n')


tic
mat2(1:100, 1:100) = false;
toc
 
17) Which is faster: using a switch statement or using a nested if­else?  Write a 
script to test this. 
 
Ch5Ex17.m 
% Test which is faster: switch or nested if-else

fprintf('First for if-else\n\n')

tic
for i = 1:1000
for j = 1:4
if j == 1
result = 11;
elseif j == 2
result = 22;
elseif j == 3
result = 46;
else
result = 6;
end
end
end
toc

fprintf('Now switch\n\n')

tic
for j = 1:1000
for k = 1:4
switch k
case 1
res = 11;
case 2
res = 22;
case 3
res = 46;
otherwise
res = 6;
end
end
end
toc
 
 
18) Vectorize this code: 
 
n = 3;
x = zeros(n);
y = x;
for i = 1:n
x(:,i) = i;
y(i,:) = i;
end
 
>> [x y] = meshgrid(1:3,1:3)
 
19)  A company is calibrating some measuring instrumentation and has measured 
the radius and height of one cylinder 10 separate times; they are in vector variables 
r and h.  Use vectorized code to find the volume from each trial, which is given by 
Πr2h.  Also use logical indexing first to make sure that all measurements were valid 
(> 0). 
 
>> r = [5.501 5.5 5.499 5.498 5.5 5.5 5.52 5.51 5.5 5.48];
>> h = [11.11 11.1 11.1 11.12 11.09 11.11 11.11 11.1 11.08 11.11];
>> all(r>0 & h>0)
ans =
1
>> vol = pi * r.^2 .* h

You might also like