2

I'm attempting to write the following program without any for or while loops:

function [B] = check(A, k)
B = [];
[nrow ncol] = size(A);
for i = 1:nrow
     for j = 1:ncol
         if mod(A(i,j),k) == 0
             B = [B;A(i,j)];
         else
             B = [B;A(i,j)*k];
        end
    end
end

Basically this program checks to see if the elements in matrix A are divisible by element k. If A(i,j) is divisible by k, then the element at A(i,j) would be placed in matrix B. If A(i,j) is not divisible by k, then the element at A(i,j) would be multiplied by k and placed in matrix B.

1
  • 1
    That will be painful, if not impossible. Commented May 24, 2015 at 21:24

4 Answers 4

7

I would do this

auxA = mod(A,k);
B = A(auxA==0) + A(auxA~=0).*k;

auxA==0 generates a matrix the same size as auxA, with 1's at the positions where the condition is true, and false in the others.

A(auxA==0) returns the value of A(i,j) where the matrix auxA==0 is 1, and 0 where auxA~=0.

Edit. You could do this in one row

B = A(mod(A,k)==0) + A(mod(A,k)~=0).*k;

But that would be less efficient since you compute mod(A,k) twice.

2

Copy A to B and then multiply the elements not divisible by k by k:

A=[1 2;3,4];
k=2;
A1=A/k;
B=A;
B(A1-fix(A1)~=0)=B(A1-fix(A1)~=0)*k;

Edit: Also without using an extra array, similar to eventHandler's idea:

B=A;
B(mod(A,k)~=0)=B(mod(A,k)~=0)*k
2

How about using recursion? Inefficient? Maybe.

function [A] = divvy(A, k, x, y)
[nrow ncol] = size(A);
if y < ncol 
    A = divvy(A, k, x, y+1)
elseif x < nrow 
    A = divvy(A, k, x+1, 1)
end

if mod(A(x,y),k) != 0
    A(x,y) = A(x,y) * k 
end

To use it, just pass x=1 and y=1.

2

Another possible solution:

B = A .* ((mod(A, k) ~= 0) * (k - 1) + 1);

Since you're scanning row by row, and B is created as a column vector, you could use this:

B = reshape((A .* ((mod(A, k) ~= 0) * (k - 1) + 1))', [], 1)
1
  • 1
    Welcome back! It has been a while since I've seen you here!
    – rayryeng
    Commented May 25, 2015 at 4:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.