# Creating a matrix from the output of a variable inside a for loop

I would like to enter the results of the following loop inside a matrix as its elements:

p=1;
q=4;

For[i = 0, i < p, i++,
For[j = 1, j < q + 1, j++,
For[h = 0, h < p, h++,
For[k = 1 , k < q + 1, k++,
Subscript[wtotal, m, i, j, h, k] =
Subscript[w, m, i, j, h, k  ] + Subscript[w1, m, i, j, h, k]
; Print[Subscript[wtotal, m, i, j, h, k]]]]
]
];


This matrix gives 16 values, so I would like to enter those 16 values inside a 4X4 matrix. So how should I do it...

Further how should i convert the 4x4x4x4 table into a 16x16 matrix so that i can take its inverse.?

• You'll want to look into using Table[] instead of For[], for starters... Oct 25, 2012 at 8:59
• You do know that Mathematica starts indexing list elements at 1 instead of 0? Oct 25, 2012 at 9:02

You can either do an iterative addition:

p = 1; q = 4;
wtotal = Table[
Subscript[w, m, i, j, h, k] + Subscript[w1, m, i, j, h, k], {i,
p}, {j, 2, q + 1}, {h, p}, {k, 2, q + 1}]


(since Mathematica starts indexing at 1, I've adjusted the iterators).

Or you can add the two tables directly:

p = 1; q = 4;
w = Table[
Subscript["w", m, i, j, h, k], {i, p}, {j, 2, q + 1}, {h, p}, {k,
2, q + 1}];
w1 = Table[
Subscript["w1", m, i, j, h, k], {i, p}, {j, 2, q + 1}, {h, p}, {k,
2, q + 1}];

wtotal = w + w1


Note that I used "w" instead of w inside subscripts to prevent a recursive calling.

• thank you very much Istvan .the code is working and has helped me a lot for my assignment. -best Pawan Oct 25, 2012 at 19:58
• @user4402: You're most welcome, have a nice time on Mathematica.SE! Oct 25, 2012 at 20:28
• i have another doubt, the matrix which i got is a 4x4x4x4 tensor, and i want to convert it into a 16x16 matrix to find its inverse, so how can i do that.? Oct 27, 2012 at 15:18
• @user4402 Which matrix do you refer to? Could you be a bit more specific? How do you want to convert it to a 2D matrix? Does Partition[Flatten[matrix, 2], 16] work for you? Oct 27, 2012 at 15:51
• I used the command of partition given by and the program worked so thank you once again..I just wanted to convert a table of 256 elements into a 16x16 matrix so i wrote the command as:-Partition[Flatten[matrix, 4], 16] Oct 29, 2012 at 13:07