Self-check exercise: Vectorized Logical Operations
In the following problems you should practice exploiting MATLAB's vectorization capabilities. In particular, avoid writing any for
and while
loops.
-
Consecutive differences and ordering
Write a function
differences
that given a vectorv
of lengthn
as input, returns a vector of lengthn-1
containing the differencesv(2)-v(1), v(3) - v(2), ..., v(n)-v(n-1)
.Write another function
isIncreasing
that given a vectorv
returns 1 if the components ofv
form an increasing sequence, i.e ifv(1) < v(2) < ...
, or returns 0, otherwise. -
Distance between two DNA strands
The "distance" between two DNA strands is a measure of how different they are. Define the distance as the number of positions where the bases on the two strands do not match.
For example, the two strands
ACTGACTTAC
ACGCAGTTAG
are different at four positions (3, 4, 6, 10), giving the distance value 4. Count the difference in strand lengths as mismatches, e.g.,
ACTGACT
ACGG
give the distance value (1+3)=7. Assume that strand 1 is longer than or equal in length to strand 2.Implement the following function without using any loops! , i.e. make efficient use of matlabs vectorization capabilities:
function dist= distance(s1, s2)
% Post: dist is the distance between DNA strands s1 and s2
% Pre: length(s1)>=length(s2)>0. Both strands contain upper case
% letters or both strands contain lower case letter.
-
Finding local maxima
Consider the following problem in signal processing. Given a vector
v = [v(1), v(2), ..., v(n) ]
we are interesting in finding the locations of its "local maxima." By a local maximum we mean a component ofv
, that is bigger than both the previous and the next component, i.e. ifi
is the index of such component, one should have bothv(i-1) < v(i)
andv(i) > v(i+1)
. Write a functionfindLocalMaxima
that takes a vector as an argument and returns a vector containing all indices at which local maxima occur. -
Filtering a matrix
Write a function
zeroEvenOrBig
that takes as input a matrixM
having integer entries and returns a matrix L in whichL(i,j) = 0
isM(i,j)
was an even number or a number greater than 1000 andL(i,j) = M(i,j)
other wise.