# How can I assign matrix values in below form? [closed] I want to create matrix as the below fig. shows. How can I do it with a do-loop, for-loop, if-loop, or any other way? Thanks a lot...

• It's an straightforward usage of SparseArray[ ] Mar 25 '16 at 21:25
• Or DiagonalMatrix with the second argument set to 1 or -1. Mar 25 '16 at 21:27
• Related: (92776), (107714), (107530).
– user31159
Mar 25 '16 at 22:37

yourMatrix[n_Integer] := SparseArray[{
{1, 1} -> 1,
{i_, j_} /; j == i - 1 -> -1/Sqrt[(2 i - 3) (2 i - 1)],
{i_, j_} /; j == i + 1 -> 1/Sqrt[(2 j - 3) (2 j - 1)]
}, {n, n}] // Normal

yourMatrix // MatrixForm • Slightly obfuscated: yourMatrix[n_Integer] := SparseArray[{{1, 1} -> 1, {i_, j_} /; Abs[i - j] == 1 :> Sign[j - i]/Sqrt[4 Min[i, j]^2 - 1]}, {n, n}] // Normal Mar 26 '16 at 1:33
• A big +1 for "fit[ing] the pattern" :D
– user31159
Mar 26 '16 at 1:35
• @Xavier I'm glad you liked my edit: I thought it would blend in better :-) Mar 26 '16 at 1:57
myMatrix[d_] := With[{c = (1/(Sqrt[2 # - 3] Sqrt[2 # - 1])) & /@ Range[2, d]},
SparseArray[{
{1, 1} -> 1,
Band[{1, 2}] -> c,
Band[{2, 1}] -> -c
}, {d, d}]
];

myMatrix // MatrixForm • You beat me to the punch :-) and using Band too, which is neater than my solution. I'll delete my answer unless I can come up with something else Mar 25 '16 at 21:45
• @Marco, you didn't need to remove it; it's nice to show the formulation with entry-by-entry rules for completeness. Mar 26 '16 at 0:45
• @J.M. I see your point. I'll undelete it, thanks! Besides, Xavier's myMatrix was feeling lonely anyway. I wonder if we could convince march to go for ourMatrix :-) Mar 26 '16 at 1:16
• Shorter: c = 1/Sqrt[4 Range[d - 1]^2 - 1] Mar 26 '16 at 2:03
ourMatrix[m_] :=
DiagonalMatrix[UnitVector[m, 1]] + # - Transpose[#] &
@DiagonalMatrix[1/Sqrt[#1 #2] & @@@ Partition[Range[1, 2 m - 1, 2], 2, 1], 1]


(Thanks to MarcoB for the heads-up about the missing 1 and J.M. for the fix; thus the ourMatrix.)

ourMatrix • It's nice to see a DiagonalMatrix approach as well. The OP's matrix has a $1$ entry in position (1, 1) though. Could you adjust your solution accordingly? Mar 26 '16 at 1:56
• A simple cure involves DiagonalMatrix[UnitVector[m, 1]]. Mar 26 '16 at 2:05
• Thanks for the heads-up, @MarcoB. Mar 26 '16 at 3:26
• Thanks for the fix, and for displaying excellent taste in variable names! What a nice, cozy family of little matrices we have on this page! :-) Mar 26 '16 at 3:38
• I concur with @MarcoB, this is a function with an exquisite name :p
– user31159
Mar 27 '16 at 1:27