Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Help with conditional loop

Subject: Help with conditional loop

From: Mukesh

Date: 7 Aug, 2012 16:50:23

Message: 1 of 2

This is not exactly a MATLAB problem, but a programming problem.

I've a very large number (num) for the loop counter. Inside I've an IF loop which will be iterated only every nth divison (num/n) of the loop counter. Obviously num/n may not be an integer, so every closest nth divison.

sample code......

num = 999999; % some large number
n = 41;
for j = 1:n;
    cntr(j) = round(num/n*j);
end
k = 0;
for i = 1:num
% some code here
    if sum(i==cntr)
% some code here
        k = k + 1;
        disp(['Loop No:' sprintf('%7.0f',i)...
              ' IF No:' sprintf('%3.0f',k)...
              ' % Done:' sprintf('%5.1f',i/num*100)]);
    end
end
% Code ends here

I don't want to create another for loop for generating the cntr vector.

How can I achieve the same without creating the cntr loop?

Thankyou

Subject: Help with conditional loop

From: dpb

Date: 7 Aug, 2012 18:00:06

Message: 2 of 2

On 8/7/2012 11:50 AM, Mukesh wrote:
...

> I've a very large number (num) for the loop counter. Inside I've an
> IF loop which will be iterated only every nth divison (num/n) of the
> loop counter. Obviously num/n may not be an integer, so every closest
> nth divison.
>
> sample code......
>
> num = 999999; % some large number n = 41; for j = 1:n; cntr(j) =
> round(num/n*j); end k = 0; for i = 1:num % some code here if
> sum(i==cntr) % some code here k = k + 1; disp(['Loop No:'
> sprintf('%7.0f',i)... ' IF No:' sprintf('%3.0f',k)... ' % Done:'
> sprintf('%5.1f',i/num*100)]); end end % Code ends here
>
> I don't want to create another for loop for generating the cntr
> vector.
>
> How can I achieve the same without creating the cntr loop?

Well, you don't need a look to prestore cntr...

cntr=round(num./n.*[1:n]);

Then

k = 1;
for i = 1:num
   if sum(i==cntr(i))
     % some code here
     k = k + 1;
     ...
   end
end

or, there's really no reason to precompute it--just compute it on the fly...

k = 1;
cntr=round(num/n);
for i = 1:num
   if sum(i==cntr)
     % some code here
     k = k + 1;
     cntr=round(num/n*k);
     ...
   end
end

--

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us