I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# Matrix with two diagonals

Matrix with two diagonals is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Draw a square matrix which has 1's on both diagonals but 0's elsewhere.
If you can please use GUI

`with Ada.Text_Io; use Ada.Text_Io;with Ada.Command_Line; procedure Matrix_With_Diagonals is    type Matrix_Type is array (Positive range <>, Positive range <>) of Character;    function Matrix_X (Length : Natural) return Matrix_Type is   begin      return M : Matrix_Type (1 .. Length, 1 .. Length) do         for Row in M'Range (1) loop            for Col in M'Range (2) loop               M (Row, Col) := (if                                  Row = Col or else                                  Row = M'Last (2) - (Col - M'First (1))                                then '1' else '0');            end loop;         end loop;      end return;   end Matrix_X;    procedure Put (M : Matrix_Type) is   begin      for Row in M'Range (1) loop         for Col in M'Range (2) loop            Put (' ');            Put (M (Row, Col));         end loop;         New_Line;      end loop;   end Put; begin   Put (Matrix_X (Length => Natural'Value (Ada.Command_Line.Argument (1)))); exception   when others =>      Put_Line ("Usage: ./matrix_with_diagonals <side-length>"); end Matrix_With_Diagonals;`

## ALGOL 68

`BEGIN # draw a matrix with 1s on the diagonals and 0s elsewhere         #    # draws a matrix with height and width = n with 1s on the diagonals #    PROC draw 2 diagonals = ( INT n )VOID:         BEGIN            INT l pos := 1;            INT r pos := n;            FOR i TO n DO                FOR j TO n DO                    print( ( " ", whole( ABS ( j = l pos OR j = rpos ), 0 ) ) )                OD;                print( ( newline ) );                l pos +:= 1;                r pos -:= 1            OD         END # draw 2 diagonals # ;    # test the draw 2 diagonals procedure #    draw 2 diagonals( 10 );    print( ( newline ) );    draw 2 diagonals( 11 )END`
Output:
``` 1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0 1
```

## APL

Works with: Dyalog APL
`twoDiagonals ← (⌽∨⊢)∘.=⍨∘⍳twoDiagonals¨ 10 11`
Output:
``` 1 0 0 0 0 0 0 0 0 1  1 0 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0  0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0  0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0  0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0  0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0  0 0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0  0 0 0 0 1 0 1 0 0 0 0
0 0 1 0 0 0 0 1 0 0  0 0 0 1 0 0 0 1 0 0 0
0 1 0 0 0 0 0 0 1 0  0 0 1 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 0 0 1  0 1 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0 1 ```

## AppleScript

### Procedural

`on twoDiagonalMatrix(n)    if (n < 2) then error "twoDiagonalMatrix() handler: parameter must be > 1."     set digits to {}    set oddness to n mod 2    repeat (n - 1 + oddness) times        set end of digits to 0    end repeat    set m to n div 2 + oddness -- Middle index of digit source list.    set item m of digits to 1     set matrix to {}    set leftLen to m - 1 -- Length of left end of each row - 1.    set rightLen to leftLen - oddness -- Length of right end ditto.    -- Assemble the first m rows from the relevant sections of 'digits'.    repeat with i from m to 1 by -1        set end of matrix to items i thru (i + leftLen) of digits & items -(i + rightLen) thru -i of digits    end repeat     -- The remaining rows are the reverse of these, not repeating the mth where n is odd.    return matrix & reverse of items 1 thru (m - oddness) of matrixend twoDiagonalMatrix -- Task code.on matrixToText(matrix, separator)    copy matrix to matrix    set astid to AppleScript's text item delimiters    set AppleScript's text item delimiters to separator    repeat with thisLine in matrix        set thisLine's contents to thisLine as text    end repeat    set AppleScript's text item delimiters to linefeed    set matrix to matrix as text    set AppleScript's text item delimiters to astid    return matrixend matrixToText return linefeed & matrixToText(twoDiagonalMatrix(7), space) & ¬    (linefeed & linefeed & matrixToText(twoDiagonalMatrix(8), space))`
Output:
`"1 0 0 0 0 0 10 1 0 0 0 1 00 0 1 0 1 0 00 0 0 1 0 0 00 0 1 0 1 0 00 1 0 0 0 1 01 0 0 0 0 0 1 1 0 0 0 0 0 0 10 1 0 0 0 0 1 00 0 1 0 0 1 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 1 0 0 1 0 00 1 0 0 0 0 1 01 0 0 0 0 0 0 1"`

### Functional

`---------------- MATRIX WITH TWO DIAGONALS --------------- -- bothDiagonals :: Int -> [[Int]]on bothDiagonals(n)    -- A square matrix of dimension n with ones    -- along both diagonals, and zeros elsewhere.    script idOrReflection        on |λ|(x, y)            ({y, 1 + n - y} contains x) as integer        end |λ|    end script     matrix(n, n, idOrReflection)end bothDiagonals  --------------------------- TEST -------------------------on run    -- Two diagonal matrices of dimensions 7 and 8     unlines(map(compose(showMatrix, bothDiagonals), ¬        {7, 8}))end run  ------------------------- GENERIC ------------------------ -- compose (<<<) :: (b -> c) -> (a -> b) -> a -> con compose(f, g)    script        property mf : mReturn(f)        property mg : mReturn(g)        on |λ|(x)            mf's |λ|(mg's |λ|(x))        end |λ|    end scriptend compose  -- enumFromTo :: Int -> Int -> [Int]on enumFromTo(m, n)    if m ≤ n then        set xs to {}        repeat with i from m to n            set end of xs to i        end repeat        xs    else        {}    end ifend enumFromTo  -- matrix :: Int -> Int -> ((Int, Int) -> a) -> [[a]]on matrix(nRows, nCols, f)    -- A matrix of a given number of columns and rows,    -- in which each value is a given function of its    -- (zero-based) column and row indices.    script go        property g : mReturn(f)'s |λ|        on |λ|(iRow)            set xs to {}            repeat with iCol from 1 to nCols                set end of xs to g(iRow, iCol)            end repeat            xs        end |λ|    end script     map(go, enumFromTo(1, nRows))end matrix  -- map :: (a -> b) -> [a] -> [b]on map(f, xs)    -- The list obtained by applying f    -- to each element of xs.    tell mReturn(f)        set lng to length of xs        set lst to {}        repeat with i from 1 to lng            set end of lst to |λ|(item i of xs, i, xs)        end repeat        return lst    end tellend map  -- mReturn :: First-class m => (a -> b) -> m (a -> b)on mReturn(f)    -- 2nd class handler function lifted into 1st class script wrapper.     if script is class of f then        f    else        script            property |λ| : f        end script    end ifend mReturn  -- showMatrix :: [[a]] -> Stringon showMatrix(rows)    -- String representation of a matrix.    script        on |λ|(cells)            unwords(map(my str, cells))        end |λ|    end script     unlines(map(result, rows)) & linefeedend showMatrix  -- str :: a -> Stringon str(x)    x as stringend str  -- unlines :: [String] -> Stringon unlines(xs)    -- A single string formed by the intercalation    -- of a list of strings with the newline character.    set {dlm, my text item delimiters} to ¬        {my text item delimiters, linefeed}    set s to xs as text    set my text item delimiters to dlm    send unlines  -- unwords :: [String] -> Stringon unwords(xs)    set {dlm, my text item delimiters} to ¬        {my text item delimiters, space}    set s to xs as text    set my text item delimiters to dlm    return send unwords`
Output:
```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

1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1```

## Arturo

`drawSquare: function [side][    loop 1..side 'x ->        print map 1..side 'y [            (any? @[x=y side=x+y-1])? -> 1 -> 0        ]] drawSquare 6print ""drawSquare 9`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1```

## AWK

` # syntax: GAWK -f MATRIX_WITH_TWO_DIAGONALS.AWKBEGIN {    for (n=6; n<=7; n++) {      for (i=1; i<=n; i++) {        for (j=1; j<=n; j++) {          tmp = (i==j || i+j==n+1) ? 1 : 0          printf("%2d",tmp)        }        printf("\n")      }      print("")    }    exit(0)} `
Output:
``` 1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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
```

## Basic

`100 REM110 REM DIAGONAL-DIAGONAL MATRIX120 REM130 LET N = 7140 DIM A(N,N)150 FOR I=1 TO N150 FOR J=1 TO N160 LET A(I,J) = 0170 NEXT J180 LET J1 = I190 LET J2 = N - I + 1200 LET A(I,J1) = 1210 LET A(I,J2) = 1220 NEXT I230 REM240 FOR I=1 TO N250 FOR J=1 TO N260 PRINT " ";A(I,J);270 NEXT J280 PRINT290 NEXT I300 END `
Output:
``` 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
```

## BCPL

`get "libhdr" let diagonals(size) be    for y = 1 to size        for x = 1 to size            do writef("%C%C",                 x=y | size-x=y-1 -> '1', '0',                x=size -> '*N', ' ') let start() be\$(  diagonals(9)    wrch('*N')    diagonals(10)\$)`
Output:
```1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1```

## C

Translation of: Wren
`#include <stdio.h> void specialMatrix(unsigned int n) {    int i, j;    for (i = 0; i < n; ++i) {        for (j = 0; j < n; ++j) {            if (i == j || i + j == n - 1) {                printf("%d ", 1);            } else {                printf("%d ", 0);            }        }        printf("\n");    }} int main() {    specialMatrix(10); // even n    printf("\n");    specialMatrix(11); // odd n    return 0;}`
Output:
```1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0 1
```

## C++

`#include <concepts>#include <iostream> // Print each element of a matrix according to a predicate.  It// will print a '1' if the predicate function is true, otherwise '0'. void PrintMatrix(std::predicate<int, int, int> auto f, int size){  for(int y = 0; y < size; y++)  {    for(int x = 0; x < size; x++)    {      std::cout << " " << f(x, y, size);    }    std::cout << "\n";  }  std::cout << "\n";} int main(){  // a lambda to create diagonals  auto diagonals = [](int x, int y, int size)  {    return x == y || ((size - x - 1) == y);  };   PrintMatrix(diagonals, 8);  PrintMatrix(diagonals, 9);}  `
Output:
``` 1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
```

## CLU

`matrix = array[array[int]] diagonals = proc (size: int) returns (matrix)    mat: matrix := matrix\$new()    for y: int in int\$from_to(1, size) do        line: array[int] := array[int]\$new()        for x: int in int\$from_to(1, size) do            n: int            if x=y cor size-x=y-1                 then n := 1                else n := 0            end            array[int]\$addh(line, n)        end        matrix\$addh(mat, line)    end    return(mat)end diagonals print_matrix = proc (s: stream, mat: matrix)    for line: array[int] in matrix\$elements(mat) do        for elem: int in array[int]\$elements(line) do               stream\$puts(s, " " || int\$unparse(elem))        end        stream\$putl(s, "")    endend print_matrix start_up = proc ()    po: stream := stream\$primary_output()    print_matrix(po, diagonals(9))    stream\$putl(po, "")    print_matrix(po, diagonals(10))end start_up`
Output:
``` 1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1```

## Draco

`proc setDiagonals([*,*] byte matrix) void:    word x, y, width, height;    width := dim(matrix, 1);    height := dim(matrix, 2);    for x from 0 upto width-1 do        for y from 0 upto height-1 do            matrix[x,y] :=                if x = y or width - x - 1 = y                    then 1                    else 0                fi        od    odcorp proc printMatrix([*,*] byte matrix) void:    word x, y, width, height;    width := dim(matrix, 1);    height := dim(matrix, 2);    for y from 0 upto height-1 do        for x from 0 upto width-1 do            write(' ', matrix[x,y]:1)        od;        writeln()    odcorp proc main() void:    [9,9] byte m_odd;    [10,10] byte m_even;     setDiagonals(m_odd);    printMatrix(m_odd);    writeln();     setDiagonals(m_even);    printMatrix(m_even)corp`
Output:
``` 1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1```

## Excel

### LAMBDA

Excel can lift functions over scalar values to functions over two-dimensional arrays.

Here we bind the name TwoDiagonalMatrix to a lambda expression in the Name Manager of the Excel WorkBook:

`TwoDiagonalMatrix=LAMBDA(n,    LET(        ixs, SEQUENCE(n, n, 0, 1),        x, MOD(ixs, n),        y, QUOTIENT(ixs, n),         IF(x = y,            1,            IF(x = (n - y) - 1, 1, 0)        )    ))`
Output:

The formulae in cells A2 and B2 populate the whole of each adjacent matrix.

 =TwoDiagonalMatrix(A2) fx A B C D E F G H I 1 N Matrix 2 7 1 0 0 0 0 0 1 3 0 1 0 0 0 1 0 4 0 0 1 0 1 0 0 5 0 0 0 1 0 0 0 6 0 0 1 0 1 0 0 7 0 1 0 0 0 1 0 8 1 0 0 0 0 0 1 9 10 8 1 0 0 0 0 0 0 1 11 0 1 0 0 0 0 1 0 12 0 0 1 0 0 1 0 0 13 0 0 0 1 1 0 0 0 14 0 0 0 1 1 0 0 0 15 0 0 1 0 0 1 0 0 16 0 1 0 0 0 0 1 0 17 1 0 0 0 0 0 0 1

Recent builds of Excel have also introduced a MAKEARRAY function, which takes a lambda expression as an argument.

Binding the name bothDiagonalMatrix in the Excel Name Manager:

`bothDiagonalMatrix=LAMBDA(n,    MAKEARRAY(        n, n,         LAMBDA(            x, y,             INT(OR(                x = y,                 x = (1 + n - y)            ))        )    ))`
Output:
 =bothDiagonalMatrix(A2) fx A B C D E F G H I 1 N Matrix 2 7 1 0 0 0 0 0 1 3 0 1 0 0 0 1 0 4 0 0 1 0 1 0 0 5 0 0 0 1 0 0 0 6 0 0 1 0 1 0 0 7 0 1 0 0 0 1 0 8 1 0 0 0 0 0 1 9 10 8 1 0 0 0 0 0 0 1 11 0 1 0 0 0 0 1 0 12 0 0 1 0 0 1 0 0 13 0 0 0 1 1 0 0 0 14 0 0 0 1 1 0 0 0 15 0 0 1 0 0 1 0 0 16 0 1 0 0 0 0 1 0 17 1 0 0 0 0 0 0 1

## F#

` // Matrix with two diagonals. Nigel Galloway: February 17th., 2022let m11 m=Array2D.init m m (fun n g->if n=g || n+g=m-1 then 1 else 0)printfn "%A\n\n%A" (m11 5) (m11 6) `
Output:
```[[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]]

[[1; 0; 0; 0; 0; 1]
[0; 1; 0; 0; 1; 0]
[0; 0; 1; 1; 0; 0]
[0; 0; 1; 1; 0; 0]
[0; 1; 0; 0; 1; 0]
[1; 0; 0; 0; 0; 1]]
```

## Factor

Works with: Factor version 0.99 2021-06-02
`USING: io kernel math math.matrices prettyprint ; : <x-matrix> ( n -- matrix )    dup dup 1 - '[ 2dup = -rot + _ = or 1 0 ? ] <matrix-by-indices> ; 6 <x-matrix> simple-table. nl7 <x-matrix> simple-table.`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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
```

## FreeBASIC

### Text based

`Sub twoDiagonalMatrix(n As Integer)    For i As Integer = 1 To n        For j As Integer = 1 To n            Print Iif((i = j) Or (i + j = n + 1), "1 ", "0 ");        Next j        Print    Next iEnd Sub twoDiagonalMatrix(6)PrinttwoDiagonalMatrix(7)Sleep`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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```

### Graphical

`Dim As Integer n = 8, size = 60 * n + 70Screenres size, size, 24ClsWindowtitle "Matrix with two diagonals" Dim As Integer beige = Rgb(245, 245, 220), brown = Rgb(171, 82, 54) For x As Integer = 0 To n    For y As Integer = 0 To n        Dim As Integer cx = x*60 + 10        Dim As Integer cy = y*60 + 10        'If (x + y) Mod 2 = 0 Then        If (x = y) Or (x + y = n) Then            Line (cx,cy) - (cx+50, cy+50), brown, BF            Draw String (cx + 20, cy + 20), "1", beige        Else            Line (cx,cy) - (cx+50, cy+50), beige, BF        End If    Next yNext xBsave "twoDiagonalMatrix.bmp",0Sleep`
Output:

## Fortran

### Free form

Works with: Fortran 95

Fortran stores data in columns. Therefore, it should be checked whether instead of filling the matrix row by row (as below) it would be better to do it column by column. The profit would be cache hit optimization, better communication between CPU and RAM. Fortran allows you to zero the entire array, such as the a array below, simply by substituting a = 0. Unfortunately, an array 100x100 (that is, the choosen maximum size) would be filled with zeros even if, as in the example, we would need a much smaller array. You can also eliminate the variables j1 and j2 by replacing them with i and n - i + 1 respectively, but the source code would be slightly less readable.

`program prog     dimension a(100, 100)     n = 7     j1 = 1    j2 = n    do i = 1, n        do j = 1, n            a(i, j) = 0.        end do        a(i, j1) = 1        a(i, j2) = 1        j1 = j1 + 1        j2 = j2 - 1    end do     do i = 1, n        print *, (a(i, j), j=1,n)    end do end `
Output:
```   1.00000000       0.00000000E+00   0.00000000E+00   0.00000000E+00   0.00000000E+00   0.00000000E+00   1.00000000
0.00000000E+00   1.00000000       0.00000000E+00   0.00000000E+00   0.00000000E+00   1.00000000       0.00000000E+00
0.00000000E+00   0.00000000E+00   1.00000000       0.00000000E+00   1.00000000       0.00000000E+00   0.00000000E+00
0.00000000E+00   0.00000000E+00   0.00000000E+00   1.00000000       0.00000000E+00   0.00000000E+00   0.00000000E+00
0.00000000E+00   0.00000000E+00   1.00000000       0.00000000E+00   1.00000000       0.00000000E+00   0.00000000E+00
0.00000000E+00   1.00000000       0.00000000E+00   0.00000000E+00   0.00000000E+00   1.00000000       0.00000000E+00
1.00000000       0.00000000E+00   0.00000000E+00   0.00000000E+00   0.00000000E+00   0.00000000E+00   1.00000000
```

### Fixed form

Works with: Fortran 77

Fortran is the oldest high-level programming language. It is constantly evolving and unfortunately there are no longer (or at least I do not have) computers on which to test whether the program works in the old Fortran IV or an even older dialect. The example below should be in Fortran IV, but unfortunately it was tested with a modern Fortran 2018 compiler, so even in legacy mode it is not Fortran IV but Fortran 77. However, it seems that it should work on CDC6000 mainframe ... if someone obviously has CDC6000.

`C DIAGONAL-DIAGONAL MATRIX IN FORTRAN 77        PROGRAM PROG        DIMENSION A(100, 100)        N = 7        A = 0.       DO 10 I = 1, N       A(I, I) = 1.  10   A(I, N - I + 1) = 1.        DO 20 I = 1, N  20   PRINT *, (A(I, J), J=1,N)        END`

## Go

Translation of: Wren
`package main import "fmt" func specialMatrix(n uint) {    for i := uint(0); i < n; i++ {        for j := uint(0); j < n; j++ {            if i == j || i+j == n-1 {                fmt.Printf("%d ", 1)            } else {                fmt.Printf("%d ", 0)            }        }        fmt.Println()    }} func main() {    specialMatrix(8) // even n    fmt.Println()    specialMatrix(9) // odd n}`
Output:
```1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
```

`---------------- MATRIX WITH TWO DIAGONALS --------------- twoDiagonalMatrix :: Int -> [[Int]]twoDiagonalMatrix n = flip (fmap . go) xs <\$> xs  where    xs = [1 .. n]    go x y      | y == x = 1      | y == succ (subtract x n) = 1      | otherwise = 0 --------------------------- TEST -------------------------main :: IO ()main =  mapM_ putStrLn \$    unlines . fmap (((' ' :) . show) =<<)      . twoDiagonalMatrix      <\$> [7, 8]`

Or, in the form of a list comprehension:

`-------------- MATRIX WITH TWO DIAGONALS --------------- twoDiagonalMatrix :: Int -> [[Int]]twoDiagonalMatrix n =  let xs = [1 .. n]   in [ [ fromEnum \$ x `elem` [y, succ (n - y)]          | x <- xs        ]        | y <- xs      ] --------------------------- TEST -------------------------main :: IO ()main =  mapM_ putStrLn \$    unlines . fmap (((' ' :) . show) =<<)      . twoDiagonalMatrix      <\$> [7, 8]`
Output:
``` 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

1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1```

and in terms of the Data.Matrix library:

`import Data.Matrix twoDiagonals :: Int -> Matrix InttwoDiagonals n =  matrix    n    n    (\(a, b) -> fromEnum \$ a `elem` [b, succ (n - b)]) main :: IO ()main =  mapM_ print \$ twoDiagonals <\$> [7, 8]`
Output:
```┌               ┐
│ 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 │
└               ┘
┌                 ┐
│ 1 0 0 0 0 0 0 1 │
│ 0 1 0 0 0 0 1 0 │
│ 0 0 1 0 0 1 0 0 │
│ 0 0 0 1 1 0 0 0 │
│ 0 0 0 1 1 0 0 0 │
│ 0 0 1 0 0 1 0 0 │
│ 0 1 0 0 0 0 1 0 │
│ 1 0 0 0 0 0 0 1 │
└                 ┘```

## J

Implementation:

`task=: {{(+.|.)=i.y}}`

In other words, generate an order n identity matrix, flip it and (treating it as a bit matrix) OR the two matrices.

Some examples:

`   task 21 11 1   task 31 0 10 1 01 0 1   task 41 0 0 10 1 1 00 1 1 01 0 0 1   task 51 0 0 0 10 1 0 1 00 0 1 0 00 1 0 1 01 0 0 0 1   task 61 0 0 0 0 10 1 0 0 1 00 0 1 1 0 00 0 1 1 0 00 1 0 0 1 01 0 0 0 0 1`

## Java

The "Java philosophy" is the object-oriented paradigm. The example solution given below is therefore somewhat incomplete. We should first declare the matrix as an interface (or abstract class), then create a whole hierarchy of subclasses where DiagonalDiagonalMatrix would be a subclass of SquareMatrix or something like that. Of course, it's a gigantic job, but as a result we would have a library competing with Matlab / Octave etc., compliant with SOLID principles.

`package example.diagdiag; public class Program {     public static void main(String[] args) {        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);        System.out.println(A);    } } class DiagonalDiagonalMatrix {     final int n;    private double[][] a = null;     public Matrix(int n) {        this.n = n;    }     public double get(int i, int j) {        if (a == null) {            return (i == j || i == n - j + 1) ? 1.0 : 0.0;        } else {            return a[i - 1][j - 1];        }    } // Not necessary for the task: a lazy creation of the dense matrix.////    public void put(int i, int j, double value) {//        if (a == null) {//            a = new double[n][n];//            for (int p = 1; p <= n; i++) {//                for (int q = 1; q <= n; j++) {//                    a[p - 1][q - 1] = get(p, q);//                }//            }//        }//        a[i - 1][j - 1] = value;//    }     @Override    public String toString() {        StringBuilder sb = new StringBuilder();        for (int i = 1; i <= n; i++) {            for (int j = 1; j <= n; j++) {                sb.append('\t');                sb.append(get(i, j));            }            sb.append('\n');        }        return sb.toString();    } }`
Output:
```	1.0	0.0	0.0	0.0	0.0	0.0	1.0
0.0	1.0	0.0	0.0	0.0	1.0	0.0
0.0	0.0	1.0	0.0	1.0	0.0	0.0
0.0	0.0	0.0	1.0	0.0	0.0	0.0
0.0	0.0	1.0	0.0	1.0	0.0	0.0
0.0	1.0	0.0	0.0	0.0	1.0	0.0
1.0	0.0	0.0	0.0	0.0	0.0	1.0```

## JavaScript

`(() => {    "use strict";     // ------------ MATRIX WITH TWO DIAGONALS ------------     // doubleDiagonal :: Int -> [[Int]]    const doubleDiagonal = n => {        // A square matrix of dimension n with ones        // along both diagonals, and zeros elsewhere.        const xs = enumFromTo(1)(n);         return xs.map(            y => xs.map(                x => Number(                    [y, 1 + n - y].includes(x)                )            )        );    };      // ---------------------- TEST -----------------------    const main = () => [7, 8].map(        n => showMatrix(            doubleDiagonal(n)        )    ).join("\n\n");      // --------------------- GENERIC ---------------------     // enumFromTo :: Int -> Int -> [Int]    const enumFromTo = m =>        n => Array.from({            length: 1 + n - m        }, (_, i) => m + i);      // showMatrix :: [[a]] -> String    const showMatrix = rows =>        // String representation of a matrix.        rows.map(            row => row.map(String).join(" ")        ).join("\n");      // MAIN --    return main();})();`

Or, in terms of a more general matrix function:

`(() => {    "use strict";     // ------------ MATRIX WITH TWO DIAGONALS ------------     // bothDiagonals :: Int -> [[Int]]    const bothDiagonals = n =>        matrix(n)(n)(            y => x => Number(                [y, (n - y) - 1].includes(x)            )        );      // ---------------------- TEST -----------------------    const main = () => [7, 8].map(        compose(            showMatrix,            bothDiagonals        )    ).join("\n\n");      // --------------------- GENERIC ---------------------     // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c    const compose = (...fs) =>        // A function defined by the right-to-left        // composition of all the functions in fs.        fs.reduce(            (f, g) => x => f(g(x)),            x => x        );      // matrix Int -> Int -> (Int -> Int -> a) -> [[a]]    const matrix = nRows => nCols =>        // A matrix of a given number of columns and rows,        // in which each value is a given function of its        // (zero-based) column and row indices.        f => Array.from({            length: nRows        }, (_, iRow) => Array.from({            length: nCols        }, (__, iCol) => f(iRow)(iCol)));      // showMatrix :: [[a]] -> String    const showMatrix = rows =>        // String representation of a matrix.        rows.map(            row => row.map(String).join(" ")        ).join("\n");     // MAIN ---    return main();})();`
Output:
```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

1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1```

## jq

Works with: jq

Works with gojq, the Go implementation of jq

`def bidiagonal_matrix:  . as \$n  | [range(0; \$n) | 0] as \$z  | reduce range(0; \$n) as \$i ([];      . + [\$z | .[\$i] = 1 | .[\$n-\$i-1] = 1] ); def display:  map(join(" ")) | join("\n");`

Example

`9|bidiagonal_matrix|display`
Output:
```1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
```

## Julia

` julia> twodiagonalmat(n) = [Int(i == j || i == n - j + 1) for j in 1:n, i in 1:n]twodiagonalmat (generic function with 1 method) julia> twodiagonalmat(1)1×1 Matrix{Int64}: 1 julia> twodiagonalmat(2)2×2 Matrix{Int64}: 1  1 1  1 julia> twodiagonalmat(3)3×3 Matrix{Int64}: 1  0  1 0  1  0 1  0  1 julia> twodiagonalmat(4)4×4 Matrix{Int64}: 1  0  0  1 0  1  1  0 0  1  1  0 1  0  0  1 julia> twodiagonalmat(5)5×5 Matrix{Int64}: 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 `

### Sparse matrix version

`julia> using LinearAlgebra julia> twodiagonalsparse(n) = I(n) .| rotl90(I(n))twodiagonalsparse (generic function with 1 method) julia> twodiagonalsparse(7)7×7 SparseArrays.SparseMatrixCSC{Bool, Int64} with 13 stored entries: 1  ⋅  ⋅  ⋅  ⋅  ⋅  1 ⋅  1  ⋅  ⋅  ⋅  1  ⋅ ⋅  ⋅  1  ⋅  1  ⋅  ⋅ ⋅  ⋅  ⋅  1  ⋅  ⋅  ⋅ ⋅  ⋅  1  ⋅  1  ⋅  ⋅ ⋅  1  ⋅  ⋅  ⋅  1  ⋅ 1  ⋅  ⋅  ⋅  ⋅  ⋅  1 julia> twodiagonalsparse(8)8×8 SparseArrays.SparseMatrixCSC{Bool, Int64} with 16 stored entries: 1  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  1 ⋅  1  ⋅  ⋅  ⋅  ⋅  1  ⋅ ⋅  ⋅  1  ⋅  ⋅  1  ⋅  ⋅ ⋅  ⋅  ⋅  1  1  ⋅  ⋅  ⋅ ⋅  ⋅  ⋅  1  1  ⋅  ⋅  ⋅ ⋅  ⋅  1  ⋅  ⋅  1  ⋅  ⋅ ⋅  1  ⋅  ⋅  ⋅  ⋅  1  ⋅ 1  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  1 `

## Matlab

`function A = diagdiag(N, sparse)% Create an diagonal-diagonal square matrix.%% Parameters:% %   N      -- number of rows (columns);%   sparse -- should be true to create a sparse matrix,%             default false (dense matrix).%% Return:%%   A matrix where all elements A(i, j) are zero except%   elements on the diagonal or on the back-diagonal.%   The diagonal (and back-diagonal) elements are equal 1.     if nargin < 2        sparse = false;    end             if sparse        A = speye(N);    else        A = eye(N);    end     A = fliplr(A);    A(1:N+1:end) = 1;end`
Output:
```>> diagdiag(7)

ans =

Columns 1 through 7

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

>> 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
```

## Pascal

`program diagonaldiagonal;const N = 7;type    index = 1..N;var     a : array[index, index] of real;    i, j, j1, j2 : index;begin    for i := 1 to N do    begin        for j := 1 to N do            a[i, j] := 0.0;        j1 := i;        j2 := N - i + 1;        a[i, j1] := 1.0;        a[i, j2] := 1.0;    end;     for i := 1 to N do    begin        for j := 1 to N do            write(a[i, j]:2:0);        writeln();    endend. `
Output:
``` 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
```

## Perl

### Strings

`#!/usr/bin/perl use strict; #https://rosettacode.org/wiki/Matrix_with_two_diagonalsuse warnings; print diagonal(\$_), "\n" for 10, 11; sub diagonal  {  my \$n =  shift() - 1;  local \$_ = 1 . 0 x (\$n - 1) . 2 . "\n" . (0 . 0 x \$n . "\n") x \$n;  1 while s/(?<=1...{\$n})0/1/s or s/(?<=2.{\$n})/2/s;  return tr/2/1/r =~ s/\B/ /gr;  }`
Output:
```1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0 1```

### Numbers

`use strict;use warnings;use feature 'say'; sub dual_diagonal {    my(\$n) = shift() - 1;    my @m;    for (0..\$n) {        my @rr = reverse my @r = ( (0) x \$_, 1, (0) x (\$n-\$_) );        push @m, [ map { \$r[\$_] or \$rr[\$_] } 0..\$n ]    }    @m} say join ' ', @\$_ for dual_diagonal(4); say '';say join ' ', @\$_ for dual_diagonal(5); `
Output:
```1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1

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```

## Phix

### numbers

Tee hee, pick the bones out of this one. Lovely.

```with javascript_semantics
for n=6 to 7 do
pp(apply(true,reinstate,{repeat(repeat(0,n),n),apply(true,sq_mul,{tagset(n),{{1,-1}}}),{{1,1}}}),{pp_Nest,1})
end for
```
Output:
```{{1,0,0,0,0,1},
{0,1,0,0,1,0},
{0,0,1,1,0,0},
{0,0,1,1,0,0},
{0,1,0,0,1,0},
{1,0,0,0,0,1}}
{{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}}
```

Slightly saner, shows sackly same stuff:

```with javascript_semantics
for n=6 to 7 do
sequence s = repeat(repeat(0,n),n)
for i=1 to n do
s[i][i] = 1
s[i][-i] = 1
end for
pp(s,{pp_Nest,1})
end for
```

### strings

```with javascript_semantics
for n=6 to 7 do
sequence s = repeat(join(repeat('0',n),' '),n)
for i=1 to n do
integer j = 2*i-1
s[i][j] = '1'
s[i][-j] = '1'
end for
printf(1,"%s\n\n",{join(s,"\n")})
end for
```
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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
```

### GUI/online

Library: Phix/pGUI
Library: Phix/online

Based on 2048#Phix, and uses the same colour and font choices. You can run this online here.

```with javascript_semantics
include pGUI.e

constant TITLE = "Strange Identity Matrices",
HELPTXT = """
Press F1 to see this help text.
Press +/- to increase or decrease the matrix size
Press 'M' for a mosaic pattern
Press 'O' for outer or four sides of a square
Press 'X' for two diagonals
The window can be fully resized
"""

function help()
IupMessage(TITLE,HELPTXT,bWrap:=false)
return IUP_IGNORE -- (don't open browser help!)
end function

Ihandle canvas, dlg
cdCanvas cddbuffer, cdcanvas

sequence board
integer n = 5,
mtype = 'X' -- (two diags) or 'O'uter or 'M'osaic

function mosaic()
for y=1 to n do
for x=1+odd(n+y) to n by 2 do
board[y][x] = "1"
end for
end for
return "mosaic"
end function

function outer()
for y=1 to n do
integer step = iff(y=1 or y=n?1:n-1)
for x=1 to n by step do
board[y][x] = "1"
end for
end for
return "four sides"
end function

function diag()
for i=1 to n do
board[i][i] = "1"
board[i][-i] = "1"
end for
return "two diagonals"
end function

function redraw_cb(Ihandle /*ih*/)
integer {dw,dh} = IupGetIntInt(canvas, "DRAWSIZE"),
ms = n*5+5,                 -- margin space
mx = min(dw,dh)-ms,         -- max size
ts = floor(mx/n),           -- max tile size
th = floor(ts/2),           -- for text posn
os = ts*n+ms,               -- overall size
ox = floor((dw-os)/2),      -- top right x
oy = floor((dh-os)/2),      -- top right y
font_size = floor((ts+10)/2)

board = repeat(repeat("0",n),n)
string title
switch mtype do
case 'M': title = mosaic()
case 'O': title = outer()
case 'X': title = diag()
end switch
IupSetStrAttribute(dlg,"TITLE","%s (%dx%d, %s)",{TITLE,n,n,title})

cdCanvasActivate(cddbuffer)
cdCanvasSetBackground(cddbuffer, #FAF8EF)
cdCanvasClear(cddbuffer)
cdCanvasRoundedBox(cddbuffer, ox, ox+os, oy, oy+os, 10, 10)
cdCanvasFont(cddbuffer, "Calibri", CD_BOLD, font_size)

integer tx = ox+5
for y=1 to n do
integer ty = oy+5
for x=1 to n do
string bxy = board[x][y]
cdCanvasSetForeground(cddbuffer, #EEE4DA)
cdCanvasRoundedBox(cddbuffer, tx, tx+ts-2, ty, ty+ts-2, 5, 5)
cdCanvasSetForeground(cddbuffer, #776E65)
cdCanvasText(cddbuffer, tx+th, ty+th, bxy)
ty += ts+5
end for
tx += ts+5
end for

cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function

function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetTextAlignment(cddbuffer, CD_CENTER)
return IUP_DEFAULT
end function

function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me)
if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work)
if c=K_F1 then return help() end if
if c='+' then n += 1 end if
if c='-' then n -= (n>1) end if
c = upper(c)
if find(c,"MOX") then mtype = c end if
IupUpdate(canvas)
return IUP_IGNORE
end function

IupOpen()
canvas = IupCanvas("RASTERSIZE=532x532")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,"MINSIZE=440x450")
IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))
IupSetAttributeHandle(NULL,"PARENTDIALOG",dlg)
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
```

## PHP

`<?php \$n = 9; // the number of rows for (\$i = 1; \$i <= \$n; \$i++) {    for (\$j = 1; \$j <= \$n; \$j++) {        echo (\$i == \$j || \$i == \$n - \$j + 1) ? ' 1' : ' 0';    }    echo "\n";} `
Output:
``` 1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
```

## Python

### Pure Python

`'''Matrix with two diagonals'''  # twoDiagonalMatrix :: Int -> [[Int]]def twoDiagonalMatrix(n):    '''A square matrix of dimension n with ones       along both diagonals, and zeros elsewhere.    '''    return matrix(        n, n, lambda row, col: int(            row in (col, 1 + (n - col))        )    )  # ------------------------- TEST -------------------------# main :: IO ()def main():    '''Matrices of dimension 7 and 8'''    for n in [7, 8]:        print(            showMatrix(                twoDiagonalMatrix(n)            ) + '\n'        )  # ----------------------- GENERIC ------------------------ # matrix :: Int -> Int -> ((Int, Int) -> a) -> [[a]]def matrix(nRows, nCols, f):    '''A matrix of a given number of columns and rows,       in which each value is a given function over the       tuple of its (one-based) row and column indices.    '''    return [        [f(y, x) for x in range(1, 1 + nCols)]        for y in range(1, 1 + nRows)    ]  # showMatrix :: [[Int]] -> Stringdef showMatrix(rows):    '''String representation of a matrix'''    return '\n'.join([        ' '.join([str(x) for x in y]) for y in rows    ])  # MAIN ---if __name__ == '__main__':    main()`
Output:
```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

1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1```

### NumPy

Library: numpy
`import numpy as np def diagdiag(n):    """    Create a diagonal-diagonal matrix     Args:        n (int): number of rows.     Returns:        a (numpy matrix): double diagonal matrix.    """    d = np.eye(n)    a = d + np.fliplr(d)    if n % 2:        k = (n - 1) // 2        a[k, k] = 1    return a print(diagdiag(7))`
Output:
```[[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.]]
```

## Quackery

`  [ [] swap dup times    [ 0 over of      1 swap i poke      1 swap i^ poke      nested rot join swap ]    drop ]                   is two-diagonals ( n --> [ )   8 two-diagonals  witheach    [ witheach [ echo sp ] cr ]  cr  9 two-diagonals  witheach    [ witheach [ echo sp ] cr ] `
Output:
```1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1

1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
```

## Raku

`sub dual-diagonal(\$n) { ([1, |(0 xx \$n-1)], *.rotate(-1) … *[*-1]).map: { [\$_ Z|| .reverse] } } .say for dual-diagonal(6);say '';.say for dual-diagonal(7);`
Output:
```[1 0 0 0 0 1]
[0 1 0 0 1 0]
[0 0 1 1 0 0]
[0 0 1 1 0 0]
[0 1 0 0 1 0]
[1 0 0 0 0 1]

[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]```

## Red

`Red[] x-matrix: function [size][    repeat i size [        repeat j size [            prin either any [i = j i + j = (size + 1)]              prin sp        ]        prin newline    ]] x-matrix 6prin newlinex-matrix 7`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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
```

## Ring

` # Project : Identity Matrix# Date    : 2022/16/02# Author  : Gal Zsolt (~ CalmoSoft ~)# Email   : <[email protected]> load "stdlib.ring"load "guilib.ring" size = 8C_Spacing = 1 C_ButtonBlueStyle   = 'border-radius:6px;color:black; background-color: blue'C_ButtonOrangeStyle = 'border-radius:6px;color:black; background-color: orange' Button = newlist(size,size)LayoutButtonRow = list(size) app = new qApp {      win = new qWidget() {	    setWindowTitle('Identity Matrix')	    move(500,100)	    reSize(600,600)	    winheight = win.height()	    fontSize = 18 + (winheight / 100)  	    LayoutButtonMain = new QVBoxLayout()				    LayoutButtonMain.setSpacing(C_Spacing)	    LayoutButtonMain.setContentsmargins(0,0,0,0) 	    for Row = 1 to size		LayoutButtonRow[Row] = new QHBoxLayout() {				       setSpacing(C_Spacing)				       setContentsmargins(0,0,0,0)				       }          	 for Col = 1 to size		     Button[Row][Col] = new QPushButton(win) {                                        setSizePolicy(1,1)                                                					} 		     LayoutButtonRow[Row].AddWidget(Button[Row][Col])			 next		 LayoutButtonMain.AddLayout(LayoutButtonRow[Row])				      next              LayoutDataRow1 = new QHBoxLayout() { setSpacing(C_Spacing) setContentsMargins(0,0,0,0) }              LayoutButtonMain.AddLayout(LayoutDataRow1)              setLayout(LayoutButtonMain)              show()   }   pBegin()   exec()   } func pBegin()     for Row = 1 to size         for Col = 1 to size              if Row = Col or Row + Col = 9                Button[Row][Col].setStyleSheet(C_ButtonOrangeStyle)                Button[Row][Col].settext("1")             else                Button[Row][Col].setStyleSheet(C_ButtonBlueStyle)                Button[Row][Col].settext("0")             ok	 next     next     score = 0 `

Outpu image:
Special identity matrix with two diagonals

## Sidef

`func dual_diagonal(n) {    n.of {|k|        var r = (k.of(0) +  + (n - k - 1).of(0))        r ~Z| r.reverse    }} dual_diagonal(5).each{.join(' ').say}; say ''dual_diagonal(6).each{.join(' ').say}`
Output:
```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

1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1
```

## Vlang

Translation of: go
`fn special_matrix(n int) {    for i in 0.. n {        for j in 0..n {            if i == j || i+j == n-1 {                print("1 ")            } else {                print("0 ")            }        }        println('')    }} fn main() {    special_matrix(6) // even n    println('')    special_matrix(5) // odd n}`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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```

## Wren

A terminal based solution as I don't like asking people to view external images.

`var specialMatrix = Fn.new { |n|    for (i in 0...n) {        for (j in 0...n) {            System.write((i == j || i + j == n - 1) ? "1 " : "0 ")        }        System.print()    }} specialMatrix.call(6)  // even nSystem.print()specialMatrix.call(7)  // odd n`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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
```

## XPL0

`proc DrawMat(S);int  S, I, J;[for I:= 0 to S-1 do    [for J:= 0 to S-1 do        Text(0, if J=I or J=S-1-I then "1 " else "0 ");    CrLf(0);    ];];[DrawMat(6);  CrLf(0); DrawMat(7);  CrLf(0);]`
Output:
```1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

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
```