[Question]
  [
## Challenge:
Given a square input matrix \$A\$, pad the matrix with one row and one column on all four sides.
* The value of each element in the top and bottom row should be the sum of the elements in each corresponding column.
* The value of each element in the left and right column should be the sum of the elements in each corresponding row.
* The value of the elements in the top left, and bottom right corner should be the sum of the elements on the diagonal
* The value of the elements in the top right, and bottom left corner should be the sum of the elements in the anti-diagonal.
### Example:
```
A = 
1   5   3
3   2   4
2   5   5
Output:
 8    6   12   12    7
 9    1    5    3    9
 9    3    2    4    9
12    2    5    5   12
 7    6   12   12    8
```
**Explanation:**
The top left and bottom right elements are the sum of the diagonal \$1+2+5=8\$. The top right and bottom left elements are the sum of the anti-diagonal \$2+2+3=7\$.
The top and bottom row (except the corners) are the sum of each of the columns in \$A\$: \$1+3+2=6\$, \$5+2+5=12\$ and \$3+4+5=12\$. Similarly, the left and right column (except the corners) are the sum of each of the rows of \$A\$: \$1+5+3=9\$, \$3+2+4=9\$ and \$2+5+5=12\$.
### Input:
* A non-empty square matrix, with non-negative integers.
* Optional format
### Output:
* The matrix padded as explained above
* Optional format, but it must be the same as the input format
## Test cases:
Use the submissions in [this challenge](https://codegolf.stackexchange.com/q/129136/31516) if you want to convert the input format to a more suitable one (for instance `[[1, 5],[0, 2]]`).
```
0
----------------
0 0 0
0 0 0
0 0 0
```
```
1 5
0 2
----------------
3 1 7 5
6 1 5 6
2 0 2 2
5 1 7 3
```
```
17   24    1    8   15
23    5    7   14   16
 4    6   13   20   22
10   12   19   21    3
11   18   25    2    9 
----------------
65   65   65   65   65   65   65
65   17   24    1    8   15   65
65   23    5    7   14   16   65
65    4    6   13   20   22   65
65   10   12   19   21    3   65
65   11   18   25    2    9   65
65   65   65   65   65   65   65
```
```
15    1    2   12
 4   10    9    7
 8    6    5   11
 3   13   14    0
----------------
30   30   30   30   30   30
30   15    1    2   12   30
30    4   10    9    7   30
30    8    6    5   11   30
30    3   13   14    0   30
30   30   30   30   30   30
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution **in each language** wins. Explanations are highly encouraged.
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
,UŒDḢ$S$€,Ṛ$j€SW€jSẋ¥€2$j"$
```
[Try it online!](https://tio.run/##y0rNyan8/18n9Ogkl4c7FqkEqzxqWqPzcOcslSwgIzgcSGQFP9zVfWgpkGWkkqWk8v///@hoQx0F01gdhWgDHQWj2FgA "Jelly – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 64 bytes
Thanks to Tom Carpenter for both saving 4 bytes, *and* correcting an error I had in the original code!
```
@(a)[b=(t=@trace)(a),c=sum(a),d=t(flip(a));z=sum(a,2),a,z;d,c,b]
```
[Try it online!](https://tio.run/##LU1BCoMwELz3FXtMYBGzVq2EgP8QDxoNFFpa2rQHP59OtIdkZ2Z3Zh4@Tt81BVcURerVpIfZqej6@Jr8qsHZu/fnnsHiogq36xNY2@1QWTRPvNmFPc9jCqrUp6AGw1RbKplkPHgLeGaCfsGPnVQ4YYJust5YwmiAoEs2iiWDaQSvA4e1goRhECHwYtP94@s9Op/KHpSdMLU21zV7kzGWqiM/N5ajTj8 "Octave – Try It Online")
**Explanation:**
```
@(a)                 % Anonymous function that takes the matrix 'a' as input
 [ ... ]             % Concatenate everything inside to a single matrix
  b=(t=@trace)(a),   % Clever trick by Tom Carpenter. Save a function handle 
                     % for 't=trace', and call it with 'a' as input
                     % Save the result in the variable 'b'
  c=sum(a)           % Sum of all columns of 'a'
  d=t(flip(a));      % Save the trace of 'a' flipped as a variable 'd', while 
                     % concatenating [b,c,d] horizontally at the same time, creating the 
                     % first row of the output
  z=sum(a,2)         % The sum of each row of the input, and store it in a variable 'z'
  ,a,z;              % Concatenate it with 'a' and 'z' again, to create the middle part of the output
 d,c,b]              % Add [d,c,b] to complete the bottom row
```
---
Note, I wrote this long after I posted the challenge.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~27~~ 26 bytes
```
,!tXswyv]GXds5L(PGPXds5L(P
```
[Try it online!](https://tio.run/##y00syfn/X0exJKK4vLIs1j0ipdjURyPAPQDK@P8/2lDBVMHYWsFYwUjBxBpImCqYxgIA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##LY69CsJAEIR7n2KsYmHgZpNLclxrkcIihcVBCChYapUQ8enPObDYZZmfj30/tle@pzGfj1taP999GdNz9dfTNE7/I1d1XVfpcssz4dFENDC0UcvDL4fZaeREOFg5e1gLYgClWaMUelBSF9GiA9VX1CLoQAMDjIVLggPMixwKyIsi20pN0YA@itoJSJYvBBLWLT8).
### Explanation
```
,        % Do the following twice
  !      %   Tranpose. Takes input implititly in the first iteration
  t      %   Duplicate
  Xs     %   Row vector with the sum of each column
  wy     %   Push a copy to the bottom of the stack
  v      %   Concatenate stack vertically. This attaches the sum of
         %   each row (first iteration) and column (second), leaving 
         %   the matrix with the correct orientation (transposed twice)
]        % End
G        % Push input again
Xds      % Column vector with the diagonal of the matrix. Sum of vector
5L(      % Write that into first and last entries of the result matrix
         % matrix; that is, its upper-left and lower-right corners
P        % Flip result matrix vertically
GP       % Push input matrix vertically flipped
Xds      % Diagonal, sum. Since the input has been vertically flipped,
         % this gives the sum of the anti-diagonal of the input.
5L(      % Write that into the upper-left and lower-right corners of
         % the verticallly flipped version of the result matrix
P        % Flip vertically again, to restore initial orientation
         % Implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
ŒDµḊṖÑµ€1¦ŒḌU
S;;S
Ç€Zµ⁺ÑÑ
```
[Try it online!](https://tio.run/##y0rNyan8///oJJdDWx/u6Hq4c9rhiYe2PmpaY3ho2dFJD3f0hHIFW1sHcx1uB4pFAWUadx2eeHji////o6MNTXUUgMAQTBqBSEOjWB2uaAUTMNsALG4JJs3B4hZgthmYBOs1NASLG4PZEBKsV8EgNhYA "Jelly – Try It Online")
Looks surprisingly different from [Erik's solution](https://codegolf.stackexchange.com/a/129734/30164).
I finally managed to understand how `¦` works (by debugging through Jelly's code, lol). Too bad it requires a `€` to work with `Ç` in my case.
### Explanation
The code uses three links. The first helper link pads a vector with its sum on both ends, the second helper link fixes two corners of the matrix and the main link calls these appropriately.
```
Ç€Zµ⁺ÑÑ    Main link. Argument: M (matrix)
Ç            Call the first helper link (pad row with sums)...
 €           ...on each row of the matrix.
  Z          Transpose, so that the second invocation uses the columns.
   µ         Begin a new monadic chain.
    ⁺        Repeat the previous chain (everything up to here).
     ÑÑ      Call the second helper link twice on the whole matrix.
S;;S    First helper link. Argument: v (1-dimensional list)
S         Sum the argument list.
 ;        Append the argument list to the sum.
  ;       Append...
   S      ...the sum of the argument list.
ŒDµḊṖÑµ€1¦ŒḌU    Second helper link. Argument: M (matrix)
ŒD                 Get the diagonals of the matrix, starting with the main diagonal.
  µ                Begin a new monadic chain.
      µ€           Perform the following actions on each diagonal...
        1¦         ...and keep the result for the first item (main diagonal):
   Ḋ                 Remove the first item (incorrect top corner).
    Ṗ                Remove the last item (incorrect bottom corner).
     Ñ               Call the first helper link on the diagonal to pad it with its sum.
          ŒḌ       Convert the diagonals back to the matrix.
            U      Reverse each row, so that consecutive calls fix the other corners.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 37 bytes
```
(d,+⌿,d∘⌽)⍪(+/,⊢,+/)⍪d∘⌽,+⌿,d←+/1 1∘⍉
```
[Try it online!](https://tio.run/##NY0xCsJAEEWv8stdNpLMZDcmxwkEbQLaeoGgkkBKayuxthXBo@xF4l@IxQ4789@8aY/9pju1/WG/LLs4zKbLXBw/WRfPtzi@bZyexuVZvN4zl6duDf7UMLtcIGk4Xaj4PkyJMk4vQQB/UHi@gGDXoLBGoStRQK1hmNot1ENQQwK0ZLiFcFBRUEFoIqyQAsLaQIV24e0aygU01nj4JAq0aKJ8oht6ahpCgsskorWwPw "APL (Dyalog Unicode) – Try It Online")
`1 1∘⍉` diagonal (lit. collapse both axes into one)
`d←` store that function as *d* and apply it to the argument
`+⌿` prepend the column sums
`d∘⌽,` prepend *d* applied to the reversed argument
`(`…`)⍪` stack the following on top:
 `+/,⊢,+/` row sums, the unmodified argument, row sums
`(`…`)⍪` stack the following on top:
 `d,+⌿,d∘⌽` applied to the argument, column sums, *d* applied to the reversed argument
[Answer]
# [Python 3](https://docs.python.org/3/), 155 bytes
This is the suggestion of @LeakyNun, which saves **54 bytes**. I then golfed it myself a bit.
```
def f(m):l=len(m);r=range(l);s=sum;b=[s(m[i][i]for i in r)];c=[s(m[i][l+~i]for i in r)];d=[*map(s,zip(*m))];return[b+d+c,*[[s(a),*a,s(a)]for a in m],c+d+b]
```
[Try it online!](https://tio.run/##dU65boQwEO3zFS5tmGJtwl6IL7FcmCtBwl5k2CIp8uvkDavdIlIkzIzf6flr/bzFYtu6fhCDDOo61VMfsVSpTj5@9HJS1VIv91A1tV1ksKPDN9ySGMUYRVKual/ElP/84braZsHPcqHvcZZZUMBSv95TtE3e5S1lFmavKPPEc3d7dgdHLRSN2@Y0xlUO0lp9ImHeSWgSZ/xLR9YUJEoSIDQTR0CYR6wgzAHHANJYtMG5AIC7YAxTI8bADurinFJvj67n3DvLvY/NSBKczmkIOvH1vJexRvO1eBTzWw7/BULOUn4bS7Zf "Python 3 – Try It Online")
# Initial solution - [Python 3](https://docs.python.org/3/), 216 bytes
```
def f(m):l=len(m);r,s=range(l),sum;a,b,c,d=s(m[i][i]for i in r),s(m[i][l-i-1]for i in r),[s(m[i][j]for j in r)for i in r],[s(m[i][j]for i in r)for j in r];print([[a]+d+[b]]+[[c[i]]+m[i]+[c[i]]for i in r]+[[b]+d+[a]])
```
[Try it online!](https://tio.run/##ZU/JboMwEL3nK@YI8kSKTclSxJdYPkCA1hE4kUkP@XryBldKFwnj8Vvt2@P@eQ3FsnT9QEM25e9jPfYBQxV5rmMTPvpszHn@mqqGWz5zV8/ZZL3DN1wjefKBIgQJHLd@q38R9pu5rOgloS@B@yPwL0HSuuoWfbhn1jZOdcq2zilrz3A4JT6V5h@JoNtV2jiXLwOc@sBk3pg00xH/EqWmYCqZQGgh9oCw7zGCMDssA0hj0AbrBADuQjDsGjEGdlAnlGzSFfPNWlauReJCBEmsxCDhIMfj2iIaLcciNcoldv@SoBON3Eae8gQ "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~268~~ ~~250~~ ~~184~~ 174 bytes
10 thanks to Stewie Griffin
```
from numpy import *
a,c,v,s=sum,trace,vstack,matrix(input())
l,r,d,e=a(s,0),a(s,1),c(s),c(fliplr(s))
print hstack((v(([[d]],r,[[e]])),v((l,s,l)),v(([[e]],r,[[d]])))).tolist()
```
[Try it online!](https://tio.run/##JY1LjsMgEET3PkUvISpFgUx@i5wEsUC2o6ABGwG2Jqf3NM6im6d6ojp96nue9La98hxpWmL6kI9pzpUOnUOPFeVZloiaXT9iLdX1v4iuZv8n/JSWKqTsAjIGjE8nCk4S7VESvShtvYJPITPLLmU/VXrvJUKsQhgzWMufjRmtlRIcBRSEL@7pbodmpTzWOfjCJ7fNGHUD6R@QAt15XyzI6DPoAmKjmrm2jOHKzEafeHTLFJPSPA9OuOC8hwyKqzQ3sGNl7T8 "Python 2 – Try It Online")
**Some explanations**
The input is uploaded as a matrix. First the code computes the sum of each column and each row using numpy.sum. Then it computes the sum of the diagonal by numpy.trace. After this it obtains the other diagonal by making a left-right flip on the matrix. Finally, it uses numpy.vstack and numpy.hstack to glue the pieces together.
[Answer]
# R, 129 bytes
```
pryr::f(t(matrix(c(d<-sum(diag(m)),c<-colSums(m),a<-sum(diag(m[(n<-nrow(m)):1,])),t(matrix(c(r<-rowSums(m),m,r),n)),a,c,d),n+2)))
```
An anonymous function that takes a square matrix as input. I'll post an explanation if there's interest.
[Answer]
# [PHP](https://php.net/), 211 bytes
```
<?foreach($_GET as$l=>$r){$y=0;foreach($r as$k=>$c){$y+=$c;$x[$k]+=$c;$l-$k?:$d+=$c;($z=count($_GET))-1-$k-$l?:$h+=$c;}$o[]=[-1=>$y]+$r+[$z=>$y];}$o[]=[-1=>$h]+$x+[$z=>$d];print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o);
```
[Try it online!](https://tio.run/##XY5NasMwEIX3OUVQZ2FjGzxOnJ@qalalF@hOiBDsBgWbWKgJJC09uzsjG9N2odEbfW@exlnXP@2cdTPYv768Ka0FilSUdBbCpJpqKgo6y9AVIyuFMXL2MM3k/3pc89iSCqdt@C6HgMWYwAYMhlUALFfchg9zLkUAyBr5Y9zyK06rIUvk8KIct9zyHv2x8@@HykZhnfnhA1r1DD7@grvK5QQ9k4ZIxSRRUEm4aWjMINsMmt0j1KGL4FNV3fV8GTLjOEPCGbTksMHxDZ02SmdIgXeTgE80zbD@gyyh24hqI50/nS97HwU4OOpfDmuo6WLZ9z8 "PHP – Try It Online")
Expanded
```
foreach($_GET as$l=>$r){
  $y=0; # sum for a row
  foreach($r as$k=>$c){
    $y+=$c; # add to sum for a row
    $x[$k]+=$c; # add to sum for a column and store in array
    $l-$k?:$d+=$c; # make the diagonal sum left to right
    ($z=count($_GET))-1-$k-$l?:$h+=$c; # make the diagonal sum right to left
  }
  $o[]=[-1=>$y]+$r+[$z=>$y]; # add to result array the actual row with sum of both sides
}
$o[]=[-1=>$h]+$x+[$z=>$d]; # add to result array the last array
print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o); #output after adding the first array to the result array
```
[Answer]
# [Python 3](https://docs.python.org/3/), 125 bytes
```
from numpy import*
f=lambda m,t=trace,s=sum:c_[r_[t(m),s(m,1),t(m[::-1])],c_[s(m,0),m.T,s(m,0)].T,r_[t(m[::-1]),s(m,1),t(m)]]
```
[Try it online!](https://tio.run/##dVDLboMwELznK3zE0bZiTcgDib/ozbIiNy1qpBiQcQ58PZk1OVRVc8Hj2Z2HGef0M/TVsnRxCKq/h3FW1zAOMW03XXvz4fPLq0CpTdFfvmlqp3toLmcbzzYVQdNUBGJNwLZp3thpR5gKW2oK7x@0Qge0Sp5rv4TauWWM1z4VXeFj9HNhLZOqSVWOlK1IGVI7gSaztXNa681fSfk/LU6iLWHzYuOA0Y4UNo/4YtuaKidhwDLYg8K5B5Q2YmVAMQCjE59AcK5rGSfDxtS59ulFZJ3jRGuknITADD4HuR5zluzw8w9IrlRZH7k8AA "Python 3 – Try It Online")
Slightly ungolfed:
```
import numpy as np
def f_expanded(m):
    return np.c_[np.r_[np.trace(m), np.sum(m, 1), np.trace(m[::-1])],
                 np.c_[np.sum(m, 0), m.T, np.sum(m, 0)].T,
                 np.r_[np.trace(m[::-1]), np.sum(m, 1), np.trace(m)]]
```
This takes input formatted as a numpy array, then uses the `np.c_` and `np.r_` indexing tools to build a new array in one go. `np.trace` and `np.sum`are used to calculate the sums along the diagonals and everywhere else, respectively. `T` is used to take the transpose before and after concatenating the sums because it's shorter than making all the arrays 2-dimensional and using `np.r_`. `m[::-1]` saves bytes when compared to `rot90(m)` or `fliplr(m)` for finding the trace for the second diagonal.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 19 bytes
```
,U$⁺Æṭj€SW€j§,"`j"Ɗ
```
[Try it online!](https://tio.run/##TU8xCsJQDN1zivBxETo0v7baE3gAUQcRXFyKF3CrIhY8g84uuoiD1U1BvEZ7kW8SrXZI8v7j5b38ZDqbzZ3z@o1ycX2si/yYlMtDb8gtue89M0nMc@OK2/meP7PicmJeEI8B1yPrFvnqtS/TbZnuGDYr7NwIjDFAiBhyBRBwt1wtsF8uFIWnMv8PiXkfbY1oy2aLG4obdgSEYMVQfVAEJAKKAFUYyUMTfWkWSCZJMsXCqFMAJJPE0aqTCDCuZYe/WN21H391w1izQQ/SRL2GCDCo4vUq1N/B@A0 "Jelly – Try It Online")
I know there's already 2 Jelly answers, but this, I think, is fairly different from them both, and is shorter.
The Footer in the TIO link converts the inputs into 2D arrays, runs the above link over them then outputs them similar to the input format.
## How it works
```
,U$⁺Æṭj€SW€j§,"`j"Ɗ - Main link. Takes a matrix A on the right
  $                 - Collect the previous two links:
 U                  -   Reverse each row of A
                        rev(A) = A with reversed rows
,                   -   Yield the pair [A, rev(A)]
   ⁺                - Do this again on [A, rev(a)]:
                      [A, rev(A)]U   -> [rev(A), A]
                      [A, rev(A)],U$ -> [[A, rev(A)], [rev(A), A]]
    Æṭ              - Take the trace of each.
                       This returns [[Tr(A), Tr(rev(A))], [Tr(rev(A)), Tr(A)]]
                       where Tr(·) returns the trace
        S           - Yield the sums of the columns of A
       €            - Over each pair in l:
      j             -   Insert the column sums between their elements
         W€         - Wrap each in an array
                  Ɗ - Group and run the previous commands on A:
            §       -   Yield the row sums of A
             ,"`    -   Pair each with itself
                 "  -   Zip the rows of A with the pairs of row sums
                j   -   Insert each row between each pair.
           j        - Insert the rows plus their sums in between the diagonal and column sums
```
[Answer]
# JavaScript (ES6), 170 bytes
```
(a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]]
```
Input and output is a 2D array of numbers.
## Explained
```
(a,                             // input matrix: a
    m=g=>a.map((_,i)=>g(i)),    // helper func m: map by index
    s=x=>eval(x.join`+`)        // helper func s: array sum
) =>
[
    [
        d = s(m(i=>a[i][i])),           // diagonal sum: d
        ...c=m(i=>s(m(j=>a[j][i]))),    // column sums: c
        g = s(m(i=>a[i][a.length-i-1])) // antidiagonal sum: g
    ],
    ...a.map(b=>[r = s(b), ...b, r]),   // all rows with row sums on each end
    [g, ...c, d]                        // same as top row, with corners flipped
]
```
## Test Snippet
Input/output has been formatted with newlines and tabs.
```
f=
(a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]]
let tests=[[[0]],[[1,5],[0,2]],[[17,24,1,8,15],[23,5,7,14,16],[4,6,13,20,22],[10,12,19,21,3],[11,18,25,2,9]],[[15,1,2,12],[4,10,9,7],[8,6,5,11],[3,13,14,0]]];
```
```
<select id=S oninput="I.value=S.selectedIndex?tests[S.value-1].map(s=>s.join`\t`).join`\n`:''"><option>Tests<option>1<option>2<option>3<option>4</select> <button onclick="O.innerHTML=I.value.trim()?f(I.value.split`\n`.map(s=>s.trim().split(/\s+/g))).map(s=>s.join`\t`).join`\n`:''">Run</button><br><textarea rows=6 cols=50 id=I></textarea><pre id=O>
```
[Answer]
## [LOGO](https://sourceforge.net/projects/fmslogo/), 198 bytes
```
to g :v[:h reduce "+ :v]
op(se :h :v :h)
end
to f :s[:a reduce "+ map[item # ?]:s][:b reduce "+ map[item # reverse ?]:s][:c apply "map se "sum :s]
op `[[,:a ,@:c ,:b],@[map "g :s][,:b ,@:c ,:a]]
end
```
The function `f` takes in a matrix as a 2D list, then output the resulting matrix. `g` is helper function.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes
```
ODŠζsζ€R€˜IÅ\OUIÅ/OVIÅ|ODXšYªsXªYšŠšsª
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f3@XognPbis9te9S0JgiIT8/xPNwa4x8KJPX9w4Bkjb9LxNGFkYdWFUccWhV5dOHRBUcXFh9a9f9/dLShjmmsTrSBjlFsLAA)
### Input
A list of lists as a representation of a matrix.
### Output
A list of lists as a representation of a matrix.
### Explanation
```
ODŠζsζ€R€˜IÅ\OUIÅ/OVIÅ|ODXšYªsXªYšŠšsª
OD                                            Sum of rows and duplicate
  Š                                           Triple swap
   ζ                                          Zip arrays (to append to the rows)
    sζ                                        Swap and do the same (to prepend to the rows)
      €R€˜                                    Reverse each row and deep flat each row, making the new rows.
          IÅ\OU                               Get the diagonal of the input, sum it and save in variable X
               IÅ/OV                          Get the anti-diagonal of the input, sum it and save in variable Y
                    IÅ|OD                     Get the columns of the input, sum it and duplicate the sums vector.
                         Xš                   Prepend variable x
                           Yª                 Append variable y
                             sXªYš            Repeat for the second row, but now the prepend and append values are switched
                                  Ššsª        Append and Prepend the new rows (first and last)
```
]