Matrix with two diagonals: Difference between revisions

Content added Content deleted
No edit summary
Line 1,352: Line 1,352:
</lang>
</lang>
=={{header|Matlab}}==
=={{header|Matlab}}==
<lang Matlab>
function A = diagdiag(N, sparse)
% Create an double-diagonal square matrix
%
% Parameters:
%
% N number of rows (columns)
% sparse should be true to create sparse matrix
%
% Return:
%
% A matrix where all elements A(i, j) are zero except
% elements on the diagonal or the back-diagonal equal 1.
if nargin < 2
sparse = false;
end
if sparse
D = speye(N);
else
D = eye(N);
end
A = D + fliplr(D);
if mod(N, 2) ~= 0
k = fix(N / 2) + 1;
A(k, k) = 1;
end
end
</lang>
{{Output}}
>> diagdiag(7)

ans =

Columns 1 through 6

1 0 0 0 0 0
0 1 0 0 0 1
0 0 1 0 1 0
0 0 0 1 0 0
0 0 1 0 1 0
0 1 0 0 0 1
1 0 0 0 0 0

Column 7

1
0
0
0
0
0
1

>> diagdiag(7, true)

ans =

(1,1) 1
(7,1) 1
(2,2) 1
(6,2) 1
(3,3) 1
(5,3) 1
(4,4) 1
(3,5) 1
(5,5) 1
(2,6) 1
(6,6) 1
(1,7) 1
(7,7) 1

=={{header|Perl}}==
=={{header|Perl}}==
===Strings===
===Strings===