I want to create the matrix H of dimensions nxn and matrix elements H(i,j). Because of the physical problem I am dealing with, it is necessary to build it in the following not trivial way.
I know how to do it in Fortran, but this time I have not been able to figure out how to do it in Wolfram Mathematica.

FORTRAN WAY:

do iy=1,n
do ix=1,n
do jy=1,n
do jx=1,n
i = ix+(iy-1)*n
j = jx+(jy-1)*n
(Now I give a list of "If" about i and j, and give values to my matrix elemnts H(i,j))
enddo
enddo
enddo
enddo

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

Have you looked at the docs for the Do command?
–
jVincentMar 25 '13 at 20:57

Are you sure you want the inner If in terms of i, j - and not in terms of ix, iy, jx, jy? The latter seems more natural and would probably make it easier to write this in a more Mathematica friendly way.
–
JensMar 25 '13 at 20:59

You can use Table to build a rank 4 array, and then use Flatten to flatten it down to a rank 2 matrix.
–
SzabolcsMar 25 '13 at 20:59

This quadruple loop is really a double loop over i and j ranging from 1 to n^2 each. That's inconsistent with claiming H is an n by n matrix:it has to be n^2 by n^2.
–
whuberMar 26 '13 at 1:53

1 Answer
1

Here is a pretty direct translation using the simple pattern do x=min,max code enddo->Do[code,{x,min,max}]. Note that because the code now comes before the iterator specification it looks like they have been reversed, they in fact traveres the same way as your Fortran code.

I just put some arbitrary If structure to show how you'd do it. This all comes fairly easy if you skim through the docs. In fact if you look at the doc for Do you'll find that it supports multiple iterators, meaning you could also put all the iterators in a single call to it:

Mathematica is a registered trademark of Wolfram Research, Inc. While the mark is used herein with the limited permission of Wolfram Research, Stack Exchange and this site disclaim all affiliation therewith.