Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Zach is potentially right in that a temporary copy of the matrix may be made to perform the first operation, although I would hazard a guess that there is some internal optimization within MATLAB that attempts to avoid this. It may be a function of the version of MATLAB you are using. I tried both of your cases in version 7.1.0.246 (a couple years old) and only saw a speed difference of about 2-2.5.</p> <p>It's possible that this may be an example of speed improvement by what's called "loop unrolling". When doing vector operations, at some level within the internal code there is likely a FOR loop which loops over the indices you are swapping. By performing the scalar operations in the second example, you are avoiding any overhead from loops. Note these two (somewhat silly) examples:</p> <pre><code>vec = [1 2 3 4]; %Example 1: for i = 1:4, vec(i) = vec(i)+1; end; %Example 2: vec(1) = vec(1)+1; vec(2) = vec(2)+1; vec(3) = vec(3)+1; vec(4) = vec(4)+1; </code></pre> <p>Admittedly, it would be much easier to simply use vector operations like:</p> <pre><code>vec = vec+1; </code></pre> <p>but the examples above are for the purpose of illustration. When I repeat each example multiple times over and time them, Example 2 is actually somewhat faster than Example 1. For a small loop with a known number (in the example, just 4), it can actually be more efficient to forgo the loop. Of course, in this particular example, the vector operation given above is actually the fastest.</p> <p>I usually follow this rule: Try a few different things, and pick the fastest for your specific problem. </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