Skip to main content

more options

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.

  1. Consecutive differences and ordering

    Write a function differences that given a vector v of length n as input, returns a vector of length n-1 containing the differences v(2)-v(1), v(3) - v(2), ..., v(n)-v(n-1).

    Write another function isIncreasing that given a vector v returns 1 if the components of v form an increasing sequence, i.e if v(1) < v(2) < ... , or returns 0, otherwise.

  2. 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.

  3. 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 of v, that is bigger than both the previous and the next component, i.e. if i is the index of such component, one should have both v(i-1) < v(i) and v(i) > v(i+1) . Write a function findLocalMaxima that takes a vector as an argument and returns a vector containing all indices at which local maxima occur.

  4. Filtering a matrix

    Write a function zeroEvenOrBig that takes as input a matrix M having integer entries and returns a matrix L in which L(i,j) = 0 is M(i,j) was an even number or a number greater than 1000 and L(i,j) = M(i,j) other wise.