Doug's MATLAB Video Tutorials

November 5th, 2010

Making a matrix in a loop in MATLAB

A for loop is used to construct a simple matrix with an underlying pattern. Pre-allocation is addressed in the second half of the video.

6 Responses to “Making a matrix in a loop in MATLAB”

  1. Oleg replied on :

    I would use:

    b = bsxfun(@plus, a, (0:4).');
    
  2. dhull replied on :

    @Oleg,

    Thank you, you are right and I can see the advantage to knowing that technique.

    I, however, have a hard time internalizing and visualizing that kind of construction. Mentally, it takes me a little longer to figure out what bsxfun does. For small matrices like this, I prefer ease of understanding to terseness of code.

    For this case, there is no appreciable performance difference, so it is a matter of taste.

    FWIW, I do not make up these cases, virtually everything on this blog comes from user questions. If someone is asking me how to make that matrix, then that tells me they are not ready for bsxfun! I only bring out the more powerful (but harder to understand) techniques for the *advanced* section of this blog.

    Thanks,
    Doug

  3. ravi replied on :

    Hi Doug, great and helpful site here!

    Here is the beginning of my code;

    r2=1
    r1=10
    a=[r2:r1];
    for r2 = r2:r1
      G = r2/3;
      sigrad2 = G*a^2;
    end
    

    This is just a simplification of a larger code but for the crux of the matter is, the for loop calculates vectors for sigrad2, but I would like to store each of the results in a matrix – I have watched the video where you build a vector with y = i+rand inside the loop but haven’t been able to extend it to my case.

    I would then like to plot each of those rows in the resultant matrix against a

    Could you please help me in building that matrix? It seems simple but I can’t figure it out

    Thanks in advance

  4. dhull replied on :

    @Ravi

    http://blogs.mathworks.com/pick/2007/08/20/matlab-basics-video/

  5. ravi replied on :

    @dhull

    Yeah I mentioned that I saw that video although that only builds a 1×10 vector but I’m not sure how to expand that code to a mxn matrix

  6. dhull replied on :

    @Ravi,

    Add a second loop outside that one that counts across the columns.

    Doug

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.