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

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

1 Answer 1


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.

  • $\begingroup$ thank you very much Istvan .the code is working and has helped me a lot for my assignment. -best Pawan $\endgroup$
    – Pawan
    Oct 25, 2012 at 19:58
  • $\begingroup$ @user4402: You're most welcome, have a nice time on Mathematica.SE! $\endgroup$ Oct 25, 2012 at 20:28
  • $\begingroup$ 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.? $\endgroup$
    – Pawan
    Oct 27, 2012 at 15:18
  • $\begingroup$ @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? $\endgroup$ Oct 27, 2012 at 15:51
  • $\begingroup$ 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] $\endgroup$
    – Pawan
    Oct 29, 2012 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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