Search Program on this blog

Wednesday 19 August 2015

Write a function called divvy that takes a matrix A of integers greater than or equal to zero and a single positive integer k as its two inputs and returns a matrix B that has the same size as A. The elements of B are all divisible by k. If an element of A is divisible by k, then the corresponding element in B must have the same value. If an element of A is not divisible by k, then the corresponding element of B must be the product of the given element of A and k. You are not allowed to use any for-­‐loops or while-­‐loops. For example, the call X = divvy([1 2 ; 3 4], 2) would make X equal to [2 2 ; 6 4].

function B = divvy(A,k)
%Input A is a matrix >=0, k is a positive integer
%Output B is a matrix
%Example: A = [1 2 ; 3 4]
%         X = divvy(A,2)
B=A;
B(mod(A,k)~=0)=A(mod(A,k)~=0).*k; %multiply with k if not divisible by k

No comments:

Post a Comment