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 z(i,j) end end
for i = 1:nRows % good for row-wise data (C,C++,pyhton etc...) for j = 1:nCols z(i,j) end end