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...
3 Answers
$\begingroup$
$\endgroup$
3
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[5] // MatrixForm
-
$\begingroup$ 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
$\endgroup$ Commented Mar 26, 2016 at 1:33 -
$\begingroup$ A big +1 for "fit[ing] the pattern" :D $\endgroup$– user31159Commented Mar 26, 2016 at 1:35
-
$\begingroup$ @Xavier I'm glad you liked my edit: I thought it would blend in better :-) $\endgroup$– MarcoBCommented Mar 26, 2016 at 1:57
$\begingroup$
$\endgroup$
4
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[5] // MatrixForm
-
$\begingroup$ 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 $\endgroup$– MarcoBCommented Mar 25, 2016 at 21:45 -
$\begingroup$ @Marco, you didn't need to remove it; it's nice to show the formulation with entry-by-entry rules for completeness. $\endgroup$ Commented Mar 26, 2016 at 0:45
-
2$\begingroup$ @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 forourMatrix
:-) $\endgroup$– MarcoBCommented Mar 26, 2016 at 1:16 -
1$\begingroup$ Shorter:
c = 1/Sqrt[4 Range[d - 1]^2 - 1]
$\endgroup$ Commented Mar 26, 2016 at 2:03
$\begingroup$
$\endgroup$
5
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[5]
-
$\begingroup$ 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? $\endgroup$– MarcoBCommented Mar 26, 2016 at 1:56 -
$\begingroup$ A simple cure involves
DiagonalMatrix[UnitVector[m, 1]]
. $\endgroup$ Commented Mar 26, 2016 at 2:05 -
-
1$\begingroup$ 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! :-) $\endgroup$– MarcoBCommented Mar 26, 2016 at 3:38
-
$\begingroup$ I concur with @MarcoB, this is a function with an exquisite name :p $\endgroup$– user31159Commented Mar 27, 2016 at 1:27
SparseArray[ ]
$\endgroup$DiagonalMatrix
with the second argument set to1
or-1
. $\endgroup$