Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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.?

share|improve this question
You'll want to look into using Table[] instead of For[], for starters... – J. M. Oct 25 '12 at 8:59
You do know that Mathematica starts indexing list elements at 1 instead of 0? – István Zachar Oct 25 '12 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.

share|improve this answer
thank you very much Istvan .the code is working and has helped me a lot for my assignment. -best Pawan – Pawan Oct 25 '12 at 19:58
@user4402: You're most welcome, have a nice time on Mathematica.SE! – István Zachar Oct 25 '12 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.? – Pawan Oct 27 '12 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? – István Zachar Oct 27 '12 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] – Pawan Oct 29 '12 at 13:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.