Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display variable value each n iterations with condition outside the loop

When I have to display the variable value every n iterations of a for loop I always do something along these lines:

for ii=1:1000
  if mod(ii,100)==0 
     display(num2str(ii))
  end
end

I was wondering if there is a way to move the if condition outside the loop in order to speed up the code. Or also if there is something different I could do.

like image 315
shamalaia Avatar asked Apr 16 '26 11:04

shamalaia


2 Answers

You can use nested loops:

N = 1000;
n = 100;
for ii = n:n:N
    for k = ii-n+1:ii-1
        thingsToDo(k);
    end
    disp(ii)
    thingsToDo(ii);
end

where thingsToDo() get the relevant counter (if needed). This a little more messy, but can save a lot of if testing.

like image 82
EBH Avatar answered Apr 19 '26 09:04

EBH


Unless the number of tested values is much larger than the number of printed values, I would not blame the if-statement. It may not seem this way at first, but printing is indeed a fairly complex task. A variable needs to be converted and sent to an output stream which is then printing in the terminal. In case you need to speed the code up, then reduce the amount of printed data.

Normally Matlab function takes vector inputs as well. This is the case for disp and display and does only take a single function call. Further, conversion to string is unnecessary before printing. Matlab should send the data to some kind of stream anyway (which may indeed take argument of type char but this is not the same char as Matlab uses), so this is probably just a waste of time. In addition to that num2str do a lot of things to ensure typesafe conversion. You already know that display is typesafe, so all these checks are redundant.

Try this instead,

q = (1:1000)'; % assuming q is some real data in your case
disp(q(mod(q,100)==0)) % this requires a single call to disp
like image 42
patrik Avatar answered Apr 19 '26 11:04

patrik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!