statsguyz
statsguyz

Reputation: 459

How to write my program without loops

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.

Upvotes: 2

Views: 284

Answers (4)

eventHandler
eventHandler

Reputation: 1211

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.

Upvotes: 7

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

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)

Upvotes: 2

albf.unicamp
albf.unicamp

Reputation: 169

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.

Upvotes: 2

Jerry
Jerry

Reputation: 4408

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

Upvotes: 2

Related Questions