Matrix with two diagonals: Difference between revisions
Add Mathematica/Wolfram Language implementation
mNo edit summary |
(Add Mathematica/Wolfram Language implementation) |
||
(3 intermediate revisions by 3 users not shown) | |||
Line 2,099:
</syntaxhighlight>
=={{header|
K6
<syntaxhighlight lang="k">diag2: {x||x}@=:
diag2 5</syntaxhighlight>
{{out}}
<pre>(1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1)</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="Mathematica">
ClearAll[CreateMatrixWithTwoDiagonals];
CreateMatrixWithTwoDiagonals[n_Integer] :=
IdentityMatrix[n] + Reverse[IdentityMatrix[n]] -
If[OddQ[n], SparseArray[{{(n + 1)/2, (n + 1)/2} -> 1}, {n, n}], 0];
CreateMatrixWithTwoDiagonals[7] // MatrixForm
</syntaxhighlight>
{{out}}
<math>
\left(
\begin{array}{ccccccc}
1 & 0 & 0 & 0 & 0 & 0 & 1 \\
0 & 1 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 1 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 1 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 1 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{array}
\right)
</math>
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">function A = diagdiag(N, sparse)
% Create an diagonal-diagonal square matrix.
Line 2,128 ⟶ 2,165:
A(1:N+1:end) = 1;
end</syntaxhighlight>
{{
<pre>
>> diagdiag(7)
Line 3,004 ⟶ 3,041:
=={{header|Wren}}==
A terminal based solution as I don't like asking people to view external images.
<syntaxhighlight lang="
for (i in 0...n) {
for (j in 0...n) {
|