Joe Talbot
Joe Talbot

Reputation: 31

How to vectorize this for loop matlab

divisible = 0;
low = input('Start Value: ');
high = input('End Value: ');
divisor = input('Divisor: ');
mask = mod([low:high],divisor);

  for index = low:high
     if mask(index) == 0
        divisible = divisible + 1;
     end
  end

The idea is to count the number of times there is no remainder.

Upvotes: 3

Views: 253

Answers (3)

R. Schifini
R. Schifini

Reputation: 9313

First, your routine will give you an error whenever low > 1 because mask will start at 1 and have high - low + 1 elements (and when asking for mask(high) you will get and error).

Second, you almost got the answer yourself:

mask = mod([low:high],divisor);

will be a vector that contains 0 that indicate that the corresponding value is divisible by the divisor. If you do mask == 0 you will get a vector of 1 and 0 (true or false).

The next step is to add all these 1 and 0:

sum(mask==0)

and so you elliminate the for...end loop

Upvotes: 0

bla
bla

Reputation: 26069

try this line instead of the loop

 divisible = sum(mask(low:high)==0);

Upvotes: 4

Colin T Bowers
Colin T Bowers

Reputation: 18580

Here is a one line solution:

%#Set the inputs
LB = 3;
UB = 28;
Divisor = 3;

%#A one-line solution
Count = sum(mod((LB:UB)', Divisor) == 0);

Upvotes: 4

Related Questions