Doug's MATLAB Video Tutorials

July 29th, 2010

How to fix common indexing errors with for loops

This video shows how to fix common errors in MATLAB when indexing into a vector or matrix in a for loop.

6 Responses to “How to fix common indexing errors with for loops”

  1. Robbie replied on :

    Is there anything wrong with using the following?

    c = [];
    for i = 1:0.5:10
    c(end+1) = i*10;
    end
    
  2. matt fig replied on :

    @Robbie,

    The code you suggest works, however it is extremely slow for larger problems when compared with constructing a pre-allocated array in a FOR loop. If you want to avoid explicit pre-allocation for some reason, you can often do something like this (which I call dynamic pre-allocation):

    cnt = 1801;
    for ii = 10:-.005:1
    d(cnt) = ii*10; % d is fixed size after first pass.
    cnt = cnt – 1;
    end

  3. Daniel Armyr replied on :

    @doug:
    Your third case is pretty much what I do on a daily basis. However, I have found myself more comfortable with the following syntax:

    inData = 1:0.5:10;
    c = nan(size(inData));
    for i = 1:length(inData)
       c(i) = inData(i)*10;
    end
    disp ( c );
    

    I also took the liberty of preallocating memory for the sake of it.

  4. Kamran replied on :

    The output of second part of your code is not the same as the first one.
    The output of the firs part is from 10 to 100 but the output of the second is from 0 to 100.

    Thank you for your great videos.

  5. dhull replied on :

    @Kamran,

    It is never claimed they have the same results.

    Doug

  6. Nike SB replied on :

    This article gives the light in which we can observe the reality. this is very nice one and gives indepth Nike SBinformation. thanks for this nice article

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.