Fortran kind of matrix creation [closed]

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


Does anybody know how to do this in Wolfram Mathematica?

-

closed as too localized by Yves Klett, Jens, Oleksandr R., m_goldberg, whuberMar 26 '13 at 1:53

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? – jVincent Mar 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. – Jens Mar 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. – Szabolcs Mar 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. – whuber Mar 26 '13 at 1:53

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.

H=ConstantArray[0,{n+(n-1)n,n+(n-1)n}];
Do[
Do[
Do[
Do[
(
i=ix+(iy-1)*n;
j=jx+(jy-1)*n;
If[j>2&&i<3,H[[i,j]]="X",H[[i,j]]="y"]
)
,{jx,1,n}]
,{jy,1,n}]
,{ix,1,n}]
,{iy,1,n}]


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:

H=ConstantArray[0,{n+(n-1)n,n+(n-1)n}];
Do[(
i=ix+(iy-1)*n;
j=jx+(jy-1)*n;
If[j>2&&i<3,H[[i,j]]="X",H[[i,j]]="y"]
),{iy,1,n},{ix,1,n},{jy,1,n},{jx,1,n}]

-
When specifying multiple iterators the order is the reverse of when you nest them. See last bullet in the Details section of the doc page. – Sjoerd C. de Vries Mar 25 '13 at 23:56