Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe I can chime in on the variation in timings between the two methods, as well as why people are getting different relative speeds.</p> <p>Before Matlab version 2008a (or a version near that release), for loops took a major hit in any Matlab code because the interpreter (a layer between the very readable script and a lower level implementation of the code) would have to re-interpret the code each time through the for loop.</p> <p>Since that release, the interpreter has gotten progressively better so, when running a modern version of Matlab, the interpreter can look at your code and say "Ah ha! I know what he is doing, let me optimize it just a bit" and avoid the hit it would otherwise take by reinterpreting the code.</p> <p>I would expect the two ways of performing matrix multiplies to evaluate in the same amount of time, why the for loop implementation runs faster is because of some detail in the optimizations of the interpreter that us mere mortals are not privy to know.</p> <p>One broad lesson we should take from this, is not all versions are equal. I do work on a couple of bleeding edge cases using two Matlab add ons, the SimBiology and the Parallel Computing Toolboxes, both of which (especially if you want them to work together) are version dependent in speed of execution, and from time to time other stability issues. As such, I keep the three most recent releases of Matlab, will test that I get the same answers out of each version, and I'll occasionally roll back to an earlier version if I find issues with some features. This is probably overkill for most people, but gives you an idea of version differences.</p> <p>Hope this helps.</p> <p>Edits:</p> <p>To clarify, code vectorization is still important. But given a script like:</p> <pre><code>x_slow = zeros(1,1e5); x_fast = zeros(1,1e5); tic; for i=1:1e5 x_slow(i) = log(i); end time_slow = toc; % evaluates for me in .0132 seconds tic; x_fast = log(1:1e5); time_fast = toc; % evaluates for me in .0055 seconds </code></pre> <p>The disparity between time_slow and time_fast has reduced in the past several versions based on improvements in the interpreter. The example I saw I believe was on 2000a vs. 2008b, but that's subject to my recollection.</p> <p>There is something else that might be going on that was addressed by Oli and Yuk. There is often a difference between the time_1 and time_2 in:</p> <pre><code>tic; x = log(1:1e5); time_1 = toc tic; x = log(1:1e5); time_2 = toc </code></pre> <p>So the test of one million evaluations vs. one evaluation is valuable, depending on where in memory x is (in cache or no).</p> <p>Hope this helps again.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload