Homework Solutions - MATLAB
Homework Solutions - MATLAB
Problem odd_index:
function out = odd_index(M)
out = M(1:2:end, 1:2:end);
end
Problem int_col:
function v = int_col(n)
v = [n 1:n-1]';
end
Note that this is just one possible solution. There are many others.
Problem rich:
function usd = rich(cent)
usd = [0.01 0.05 0.10 0.25] * cent';
end
We use the fact that matrix multiplication sums up a set of products. Multiplying a row
vector with a column vector will result in a scalar. Here it performs the exact calculations
we need.
Problem light_time:
function [mins km] = light_time(mile)
km = mile * 1.609;
mins = km / 3e5 / 60;
end
Problem pitty:
function c = pitty(ab)
c = sqrt(ab(:,1) .^ 2 + ab(:,2) .^2);
end
Here we use the fact that the function sum works column by column. So, transposing and
then squaring every element will put the squares of the corresponding a-s and b-s into
columns. The function sum then adds them up, and sqrt computes each element's
square root. Finally, we need to transpose the result back into a column vector.
Problem bottom_left:
function M = bottom_left(N,n)
M = N(end-n+1:end, 1:n);
end
We need the last n rows and the first n columns. The only trick here is that we need endn+1, because end-n:end would get us n+1 indexes and not n as required.
Problem mean_squares:
function mm = mean_squares(nn)
mm = mean((1:nn).^2);
end
Problem hulk:
function H = hulk(v)
H = [v' (v').^2 (v').^3];
end
Solutions to Homework 4
Problem quadrants:
function Q = quadrants(n)
a = ones(n);
Q = [a 2*a ; 3*a 4*a];
end
Problem checkerboard:
function b = checkerboard(n,m)
b = ones(n,m);
b(1:2:n,2:2:m) = 0;
b(2:2:n,1:2:m) = 0;
end
Problem randomness:
function r = randomness(limit,n,m)
r = fix(limit * rand(n,m)) + 1;
end
Problem mtable:
function [t s] = mtable(n,m)
t = (1:n)' * (1:m);
s = sum(t(:));
end
Problem identity:
function I = identity(n)
I = zeros(n);
I(1 : n+1 : n^2) = 1;
end
Here we index into a matrix with a single index and MATLAB handles it as if it was a
vector using column-major order. Putting ones at the first position and jumping n+1 every
time, will put them exactly in the diagonal.
Solutions to Homework 5
Here are the "official" solutions. Note that there are multiple ways to solve any non-trivial problem,
so these are just representative examples.
Problem generationXYZ
function gen = generationXYZ(year)
if year < 1966
gen = 'O';
elseif year < 1981
gen = 'X';
elseif year < 2000
gen = 'Y';
elseif year < 2013
gen = 'Z';
else
gen = 'K';
end
end
Problem letter_grade
function G = letter_grade(score)
if score >= 91
G = 'A';
elseif score >= 81
G = 'B';
elseif score >= 71
G = 'C';
elseif score >= 61
G = 'D';
else
G = 'F';
end
end
Problem sort3
Using no built-in functions
function v = sort3(a, b, c)
if a <= b
v = [a b];
else
v = [b a];
end
if c >= v(2)
v = [v c];
% at the beginning
Problem sort3
Using no if-statements.
function v = sort3 (a,b,c)
v = [a b c];
% unordered
Problem classify
function c = classify(x)
[row, col] = size(x);
if row == 0 || col == 0
c = -1;
elseif row == 1 && col == 1
c = 0;
elseif row == 1 || col == 1
c = 1;
else
c = 2;
end
end
maxdim = max(size(x));
if mindim == 0
c = -1
elseif maxdim == 1 % otherwise, both dim == 1 (since max == 1) -> scalar
c = 0;
elseif mindim == 1 % otherwise, if the smaller dim == 1 -> vector
c = 1;
else
c = 2;
end
end
% Note that the first two solutions are longer but easier to read and understand than this
one.
Problem older
function a = older(y1,m1,d1,y2,m2,d2)
a = 1;
if y1 == y2 && m1 == m2 && d1 == d2
a = 0;
elseif (y1 > y2) || (y1 == y2 && m1 > m2) || (y1 == y2 && m1 == m2 && d1 > d2)
a = -1;
end
end
a2 = y2 * 366 + m2 * 31 + d2;
a = sign(a2 - a1);
end
Problem movies
function cando = movies(hr1,min1,durmin1,hr2,min2,durmin2)
cando = false;
endtime = hr1*60 + min1 + durmin1;
Problem sines
function [s1 s2 sums] = sines(pts,amp,f1,f2)
if nargin < 1, pts = 1000;
end
end
end
xp = [xp(2:end),x];
end
a = mean(xp);
end
Solutions to Homework 6
Problem neighbor
function w = neighbor(v)
w = [];
if min(size(v)) == 1
% must be a vector
for ii = 1:length(v)-1
% of length (n-1)
end
Problem replace_me
builds up the output one element at a time
function w = replace_me(v,a,b,c)
if nargin < 3
b = 0;
end
if nargin < 4
c = b;
end
w = [];
for k = 1:length(v);
if v(k) == a
% if a is found,
w = [w,b,c];
else
% otherwise,
wi = 1;
for vi = 1:length(v)
if v(vi) == a
w = [w(1:wi-1) b c w(wi+1:end)];
wi = wi + 1;
% increment wi
end
wi = wi + 1;
end
end
Problem halfsum
using nested loops
function s = halfsum(A)
[row col] = size(A);
s = 0;
for ii = 1:row
for jj = ii:col
s = s + A(ii,jj);
end
end
end
s = s + sum(A(r,r:end));
(inclusive)
end
end
Problem large_elements
function found = large_element(A)
problem one_per_n
using while-loop
function n = one_per_n(x)
n = 0;
sum = 0;
while sum < x && n <= 10000
n = n + 1;
sum = sum + 1/n;
end
if n > 10000
n = -1;
end
end
for n = 1:1e4
s = s + 1/n;
if s >= x
return;
end
end
n = -1;
end
Problem approximate_pi
function [a,k] = approximate_pi(delta)
k = 0;
f = sqrt(12);
a = f;
a = a + f*(-3)^(-k)/(2*k+1);
end
end
Problem separate_by_two
using division and rounding
function [even,odd] = separate_by_two(A)
even = A(fix(A/2) == A/2)'; % if A is even, rounding does not do anything to A/2
odd = A(fix(A/2) ~= A/2)'; % if A is odd, it gets rid of the .5 part, so they won't be
equal
end
% note that this will put non-integers into odd
need to negate it
odd = A(mod2)';
end
% note that this will put non-integers into odd
Problem divvy
function A = divvy (A,k)
L = (mod(A,k) ~= 0);
A(L) = k * A(L);
them by k
end
% uses A as both input and output, so we only need to modify some elements of A
Problem square_wave
using a for-loop
function sq = square_wave(n)
t = 0 : 4*pi/1000 : 4*pi;
sq = zeros(1,length(t));
% initialize output to 0
for ii = 1:2:2*n
sq = sq + cos(ii*t-pi/2)/ii;
end
end
Problem my_prime
using a for-loop
function a = myprime(n)
a = false;
if n > 1
for ii = 2:sqrt(n)
if ~mod(n,ii)
return;
end
end
a = true;
end
end
% x is prime if it is NOT divisible by all integers from 2 to sqrt(x)
% because factors have to come in pairs -- one bigger than sqrt(x) and
% one smaller (or both equal)
Solutions to Homework 7
Problem integerize
traditional solution with a single if-elseif-statement
function name = integerize(A)
mx = max(A(:));
name = 'NONE';
if mx <= intmax('uint8')
name = 'uint8';
elseif mx <= intmax('uint16')
name = 'uint16';
elseif mx <= intmax('uint32')
name = 'uint32';
elseif mx < intmax('uint64')
name = 'uint64';
end
end
break;
end
end
end
Problem May2015
function sub_May2015
days = ['Thu'; 'Fri'; 'Sat'; 'Sun'; 'Mon'; 'Tue'; 'Wed' ];
for ii = 1:31
m(ii).month = 'May';
m(ii).date = ii;
m(ii).day = days(rem(ii,7)+1,:); % +1 is needed because 0 is an invalid index
end
end
Problem June2015
traditional solution with a for-loop
function m = June2015
days = [ 'Sun'; 'Mon'; 'Tue'; 'Wed'; 'Thu'; 'Fri'; 'Sat'];
for ii = 1:30
m{ii,1} = 'June';
m{ii,2} = ii;
m{ii,3} = days(rem(ii,7)+1,:);
end
end
Problem codeit
traditional solution, looking at one char at a time
function out = codeit(in)
for ii = 1:length(in)
if in(ii) <= 'z' && in(ii) >= 'a'
out(ii) = 'a' + 'z' - in(ii);
% lower case
% encrypt it
elseif in(ii) <= 'Z' && in(ii) >= 'A' % upper case
out(ii) = 'A' + 'Z' - in(ii);
else
out(ii) = in(ii);
end
end
end
% encrypt it
% everything else
% no change needed
% identify uppercase
Problem dial
translating the actual requirements straight to code works, but it is pretty long and somewhat
awkward
function ph = dial(str)
code = {'ABC'; 'DEF'; 'GHI'; 'JKL'; 'MNO'; 'PRS'; 'TUV'; 'WXY'};
ph = str;
for ii = 1:length(str)
c = str(ii);
continue;
elseif (c >= '0' && c <= '9') || c == '#' || c == '*'
continue;
else
n = -1;
for jj = 1:length(code)
if ~isempty(strfind(code{jj},c)) % looking for legal letters
n = jj + 1;
break;
end
end
if n == -1
ph = [];
return;
end
ph(ii) = char('0' + n); % otherwise, add the char for the right number
end
end
end
n = str-' '+1; % creates a vector of indexes into code from the input characters
% the first two sum()-s check for out-of-range input (smaller than space or larger than
Y)
% the third sum() checks for any input char mapping to x, that is, illegal input
if ~((sum(n <= 0) + sum(n > length(code))) || sum(code(n) == 'x'))
ph = code(n); % a single assignment does the actual transformation of the input
string
end
end
Problem replace
using a for-loop and logical indexing
function strs = replace(strs,c1,c2);
for ii=1:length(strs)
strs{ii}(strs{ii} == c1) = c2;
end
end
Problem roman
problem size is small, so it is easier to simply enumerate all 20 numbers
function num = roman(rom)
romans = { 'I' 'II' 'III' 'IV' 'V' 'VI' 'VII' 'VIII' 'IX' 'X' ...
'XI' 'XII' 'XIII' 'XIV' 'XV' 'XVI' 'XVII' 'XVIII' 'XIX' 'XX'};
num = uint8(0);
for ii = 1:20
if strcmp(rom,romans{ii})
num = uint8(ii);
break
end
end
end
if isempty(ar)
ar = 0;
end
ar = uint8(ar);
% convert to uint8
end
Problem censor
function out = censor(strs,str)
out = {};
for ii = 1:length(strs)