The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: double for loop
Replies: 5   Last Post: Sep 9, 2013 10:29 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Nasser Abbasi

Posts: 6,486
Registered: 2/7/05
Re: double for loop
Posted: Sep 9, 2013 6:41 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

On 9/9/2013 5:20 AM, cwc wrote:
> Can someone explain to me the mechanics for a double for loop?
> [x,y] = size(z)
> for ii = 1:x;
> for jj = 1:y;
> newz = z(ii,jj)
> end
> what is the sequence being played out? A geometric interpretation would be good.

There is matrix z with x rows and y columns.

The loops scan (traverse) this 2D matrix row by row, top to down.

If you think of a 2D matrix as a page in a book, with 'y'
words on each line, and with 'x' lines per page, then it
is like reading from top to down. word on line 3 and column
5 is z(3,5)

ii is the current line number, and jj is the current word
number on current line number ii.

This is all just for visualization. In memory ofcourse, there
is no such thing. All data is stored sequentially (linear) and
the code generated by compiler/run-time, sorts out thing for
you, so you do not have to worry about indexing.

Matlab uses column major (like Fortran). i.e. the data is
stored sequentially by columns: first column data,
followed by second column data, etc...

This can have an effect on the algorithm speed. If you scan
a matrix row-wise, and the matrix is too large, then you will
be jumping from one column to the next in each step, and if
each column is too long, then matrix data will be in cache.

This can be less efficient if the data is stored Fortran-wise
since a cache miss can result requiring memory fetch, which
slower than using the data from cache. So sometimes you
see code written to scan a matrix up-down, left to right

for j = 1:nCols %good for column-wise data (Matlab,Fortran...)
for i = 1:nRows


for i = 1:nRows % good for row-wise data (C,C++,pyhton etc...)
for j = 1:nCols


Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2017. All Rights Reserved.