# Constructing matrix elements using functions and looping

**URL:** <https://community.wolfram.com/t/constructing-matrix-elements-using-functions-and-looping/2596>\
**Category:** Questions\
**Tags:** physics, mathematica, algebra, numerical-computation\
**Created:** [July 10, 2014, 1:02pm UTC](https://community.wolfram.com/t/constructing-matrix-elements-using-functions-and-looping/2596 "2014-07-10T13:02:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hbarhbar](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/hbarhbar/32/11121_2.png) [@hbarhbar](https://community.wolfram.com/u/hbarhbar)\
**Post date:** [July 10, 2014, 1:02pm UTC](https://community.wolfram.com/t/constructing-matrix-elements-using-functions-and-looping/2596/1 "2014-07-10T13:02:06Z")

</div>

Hi I’m trying to construct a tridiagonal matrix which contains a function f(x,y)=2(cos x+cosy).  
My code is:

```
Nmax = 2;
For[iw = 1, iw <= 5, iw++, 
 A[x_, y_] := 
  Normal[SparseArray[{{i_, j_} /; j == i :> 
      iw + 2 (Cos[x] + Cos[y]), {i_, j_} /; j - i == 1 :> 
      1, {i_, j_} /; i - j == 1 :> 1}, {Nmax, Nmax}]];
 Print["Testing A-matrix at (x,y)=(\[Pi]/2,\[Pi]/2)"];
 MatrixForm[A[Pi/2, Pi/2]] // N
 ]
MatrixForm[A[Pi/2, Pi/2]] // N

```

Why does it fail to show the matrix inside the For-loop?

Thanks

---

<div class="post-metadata">

**Author:** ![dreiss](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/dreiss/32/29094_2.png) [@dreiss](https://community.wolfram.com/u/dreiss)\
**Post date:** [July 10, 2014, 2:06pm UTC](https://community.wolfram.com/t/constructing-matrix-elements-using-functions-and-looping/2596/2 "2014-07-10T14:06:51Z")

</div>

A For loop, like a Do loop, does not produce an output–it simply executes the code within.  
So you could get what you are wishing for by adding a Print statement to the MatrixForm expression that you want to see as in:

```
Nmax = 2;
For[iw = 1, iw <= 5, iw++, 
 A[x_, y_] := 
  Normal[SparseArray[{{i_, j_} /; j == i :> 
      iw + 2 (Cos[x] + Cos[y]), {i_, j_} /; j - i == 1 :> 
      1, {i_, j_} /; i - j == 1 :> 1}, {Nmax, Nmax}]];
 Print["Testing A-matrix at (x,y)=(\[Pi]/2,\[Pi]/2)"];
 Print@MatrixForm[A[Pi/2, Pi/2]] // N]
MatrixForm[A[Pi/2, Pi/2]] // N

```
