Construct the Identity Matrix

44

6

The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.

This is , so the shortest code in bytes wins.

Seadrus

Posted 2016-01-28T18:17:24.087

Reputation: 1 291

1Given an integer input n ... -- I assume you mean a natural number? – Jonathan Frech – 2018-08-28T17:00:41.453

Answers

26

MATL, 2 bytes

Xy

A translation of my Octave answer.

Try it online.

A 4 byte version with no built-ins (thanks to Luis Mendo):

:t!=
:     take input n and a generate row array [1,2,...n]
 t    duplicate
  !   zip
   =  thread compare over the result

a spaghetto

Posted 2016-01-28T18:17:24.087

Reputation: 10 647

7It must have been difficult, to translate this very sophisticated code :D – flawr – 2016-01-28T18:40:12.223

11@flawr You have no idea. This is truly my masterpiece. – a spaghetto – 2016-01-28T18:40:30.330

2This seems vaguely familiar... ;) – Conor O'Brien – 2016-01-28T18:42:06.870

1Now I see why you were asking! :-D – Luis Mendo – 2016-01-28T18:54:30.947

5Without builtins: :t!= – Luis Mendo – 2016-01-28T18:56:32.997

20

TI-BASIC, 2 bytes

identity(Ans

Fun fact: The shortest way to get a list {N,N} is dim(identity(N.

Here's the shortest way without the builtin, in 8 bytes:

randM(Ans,Ans)^0

randM( creates a random matrix with entries all integers between -9 and 9 inclusive (that sounds oddly specific because it is). We then take this matrix to the 0th power.

lirtosiast

Posted 2016-01-28T18:17:24.087

Reputation: 20 331

1"that sounds oddly specific because it is" TI-BASIC is weird. O_o – Doorknob – 2016-01-29T13:48:03.280

Hell yes. TI-BASIC. +1 – bearacuda13 – 2017-06-30T19:40:01.740

isn't the shortest way to get a list {N,N}, umm, {N,N}? – Cyoce – 2017-07-02T23:05:25.793

1@Cyoce No; dim( and identity( are each one byte because TI-BASIC is tokenized. – lirtosiast – 2017-07-03T21:45:57.583

19

Julia, 9 3 bytes

eye

This is just a built-in function that accepts an integer n and returns an nxn Array{Float64,2} (i.e. a 2D array). Call it like eye(n).

Note that submissions of this form are acceptable per this policy.

Alex A.

Posted 2016-01-28T18:17:24.087

Reputation: 23 761

I see what you did there! Nice one! – Ismael Miguel – 2016-01-29T21:41:43.400

This also works in Math.JS

– ATaco – 2017-06-29T06:53:51.790

16

APL, 5 bytes

∘.=⍨⍳

This is a monadic function train that accepts an integer on the right and returns the identity matrix.

Try it here

Alex A.

Posted 2016-01-28T18:17:24.087

Reputation: 23 761

14

Octave, 10 4 bytes

@eye

Returns an anonymous function that takes a number n and returns the identity matrix.

a spaghetto

Posted 2016-01-28T18:17:24.087

Reputation: 10 647

@eye is sufficient. – flawr – 2016-01-28T18:37:28.637

@flawr Thanks, I knew there was a way to do it like that but I always forget :P – a spaghetto – 2016-01-28T18:39:16.950

eye produces the identity matrix in a lot/some numerically oriented languages. – flawr – 2016-01-28T18:50:23.733

What does the @ do? – Cyoce – 2017-07-02T23:06:17.447

@Cyoce @ is the "function handle operator", it works like a lambda and also as a reference to a particular function, so for instance, @(x)x.^2 is the squaring function and @sqrt is a reference to the square root function. You can read more about that here

– Giuseppe – 2018-01-03T18:29:40.203

12

R, 4 bytes

diag

When given a matrix, diag returns the diagonal of the matrix. However, when given an integer n, diag(n) returns the identity matrix.

Try it online

Alex A.

Posted 2016-01-28T18:17:24.087

Reputation: 23 761

12

Python 2, 42 bytes

lambda n:zip(*[iter(([1]+[0]*n)*n)]*n)[:n]

An anonymous function, produces output like [(1, 0, 0), (0, 1, 0), (0, 0, 1)],

First, creates the list ([1]+[0]*n)*n, which for n=3 looks like

[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

Using the zip/iter trick zip(*[iter(_)]*n to make groups of n gives

[(1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]

Note that the 1 comes one index later each time, giving the identity matrix. But, there's an extra all-zero row, which is removed with [:n].

xnor

Posted 2016-01-28T18:17:24.087

Reputation: 115 687

1Damn that zip/iter trick is ingenious – seequ – 2016-02-09T20:58:16.680

10

Jelly, 4 bytes

R=€R

Doesn't use a built-in. Try it online!

How it works

R=€R    Main link. Input: n

R       Range; yield [1, ..., n].
   R    Range; yield [1, ..., n].
 =€     Compare each.
        This compares each element of the left list with the right list, so it
        yields [1 = [1, ..., n], ..., n = [1, ..., n]], where comparison is
        performed on the integers.

Dennis

Posted 2016-01-28T18:17:24.087

Reputation: 196 637

25This code is unacceptably long. – flawr – 2016-01-28T18:53:00.700

5@flawr Twice the length of the shortest one. That's indeed an unusual encounter. – Rainer P. – 2016-01-28T18:55:28.297

1

@flawr Yes, and no shorter than J. FAIL!

– Adám – 2016-02-10T15:27:21.487

2In modern versions of Jelly, is two bytes, and makes fun of the longer answers. – Lynn – 2016-08-19T09:57:58.707

@Lynn That's still twice as long as the shortest oneS. – Adám – 2016-08-21T18:29:38.853

10

J, 4 bytes

=@i.

This is a function that takes an integer and returns the matrix.

marinus

Posted 2016-01-28T18:17:24.087

Reputation: 30 224

I think you can do it in 3: =i. – Sam Elliott – 2016-09-21T18:39:40.777

@SamElliott that doesn't work. For example, (=i.) 10 => 0 0 0 0 0 0 0 0 0 0 – Cyoce – 2017-07-03T00:03:43.323

9

Haskell, 43 37 bytes

f n=[[0^abs(x-y)|y<-[1..n]]|x<-[1..n]]

Pretty straightforward, though I think one can do better (without a language that already has this function built in, as many have done).

Edit: dropped some bytes thanks to Ørjan Johansen

Sheridan Grant

Posted 2016-01-28T18:17:24.087

Reputation: 191

7You can cheat the fromEnum as sum[1|x==y]. – xnor – 2016-01-29T00:31:02.737

pretty sure you can remove the space in fromEnum (y==x) – Cyoce – 2017-07-02T23:07:48.273

@xnor One byte shorter than that: 0^abs(x-y). – Ørjan Johansen – 2018-01-03T16:56:15.937

1@xnor Oh, you just used 0^(x-y)^2 yourself in another answer, even shorter. – Ørjan Johansen – 2018-01-03T18:12:40.737

@ØrjanJohansen Yes, seeing your comment was nice timing :) – xnor – 2018-01-03T18:16:52.340

8

Pyth, 7 bytes

XRm0Q1Q

Try it online: Demonstration

Creating a matrix of zeros and replacing the diagonal elements with ones.

Jakube

Posted 2016-01-28T18:17:24.087

Reputation: 21 462

You can save one byte by removing the final Q – Jim – 2017-06-22T18:43:27.820

1@jim Thanks, but that would actually be not allowed. The feature (implicit Q at the end) was implemented after the challenge was posted. – Jakube – 2017-06-22T22:40:30.297

7

JavaScript ES6, 68 62 52 bytes

Saved 10 bytes thanks to a neat trick from @Neil

x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z)))

Trying a different approach than @Cᴏɴᴏʀ O'Bʀɪᴇɴ's. Could possibly be improved.

ETHproductions

Posted 2016-01-28T18:17:24.087

Reputation: 47 880

This was exactly what I wrote before I scrolled down to find out that you'd beaten me to it. – Neil – 2016-01-28T19:57:19.150

So, in response to your challenge, I give you the (in hindsight) obvious x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z))) for a saving of 10 bytes. – Neil – 2016-01-28T19:59:43.260

@Neil Thanks a lot! I'll mention that it's your trick in the answer. – ETHproductions – 2016-01-28T20:12:57.263

x=>[...Array(x)].map((_,y,x)=>x.map(_=>+!y--)) – l4m2 – 2018-04-25T17:47:15.777

7

Retina, 25

Credit to @randomra and @Martin for extra golfing.

\B.
 0
+`(.*) 0$
$0¶0 $1

Try it online.

Note this takes input as a unary. If this is not acceptable, then decimal input may be given as follows:

Retina, 34

.+
$0$*1
\B.
 0
+`(.*) 0$
$0¶0 $1

Try it online.

Digital Trauma

Posted 2016-01-28T18:17:24.087

Reputation: 64 644

3...whoa. Retina is becoming powerful as a language for more than regex. – ETHproductions – 2016-01-28T21:02:16.570

@ETHproductions yes, though this is answer pretty much all regex substitution. The only special thing is the use of $*0 to replace a number n with n 0s. – Digital Trauma – 2016-01-28T21:06:50.197

6

Python 3, 48

Saved 1 byte thanks to sp3000.

I love challenges I can solve in one line. Pretty simple, build a line out of 1 and 0 equal to the length of the int passed in. Outputs as a 2d array. If you wrap the part after the : in '\n'.join(), it'll pretty print it.

lambda x:[[0]*i+[1]+[0]*(x+~i)for i in range(x)]

Morgan Thrapp

Posted 2016-01-28T18:17:24.087

Reputation: 3 574

2x-i-1 -> x+~i – Sp3000 – 2016-01-28T21:58:02.707

6

Haskell, 54 bytes

(#)=replicate
f n=map(\x->x#0++[1]++(n-x-1)#0)[0..n-1]

f returns the identity matrix for input n. Far from optimal.

ThreeFx

Posted 2016-01-28T18:17:24.087

Reputation: 1 435

You can save a handful of bytes using a list comprehension instead of a map call. – MathematicalOrchid – 2016-01-29T09:23:32.757

6

Lua, 77 75 65 bytes

x,v=z.rep,io.read()for a=1,v do print(x(0,a-1)..'1'..x(0,v-a))end

Well, I'm not sure if lua is the best language for this with the two period concatenation... But hey, there's a shot at it. I'll see if there's any improvements to be made.

EDIT:

I figured something out on accident which I find rather odd, but, it works.

In Lua, everyone knows you have the ability to assign functions to variables. This is one of the more useful CodeGolf features.

This means instead of:

string.sub("50", 1, 1) -- = 5
string.sub("50", 2, 2) -- = 0
string.sub("40", 1, 1) -- = 4
string.sub("40", 2, 2) -- = 0

You can do this:

s = string.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

But wait, Lua allows some amount of OOP. So you could potentially even do:

z=""
s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

That will work as well and cuts characters.

Now here comes the weird part. You don't even need to assign a string at any point. Simply doing:

s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

Will work.


So you can visually see the difference, take a look at the golfed results of this:

Using string.sub (88 characters)

string.sub("50", 1, 1)string.sub("50", 2, 2)string.sub("40", 1, 1)string.sub("40", 2, 2)

Assigning string.sub to a variable (65 characters)

s=string.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

Assigning string.sub using an OOP approach (64 characters)

z=""s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

Assigning string.sub using a.. nil approach? (60 characters)

s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

If someone knows why this works, I'd be interested.

Skyl3r

Posted 2016-01-28T18:17:24.087

Reputation: 399

The "z.rep" line is breaking on mine. I'm betting there should be a z='' somewhere? A shorter variant of z=''z.rep would just be ('').rep .

You can also use the cmdline ... for reading input, and widdle the bytecount down to 57 as follows: z='0'for i=1,...do print(z:rep(i-1)..1 ..z:rep(...-i))end – thenumbernine – 2016-03-22T11:39:18.017

I found someone suggesting ("").rep before, but I was unable to get it to work. It'd always error out. Maybe my interpreter is the problem here. I'm struggling to find any documentation on this command line input, do you know where it can be found? – Skyl3r – 2016-03-23T12:51:43.157

5

C, 59 or 59 56 or 56

Two versions of identical length.

3 bytes saved due to suggestion from anatolyg: (n+1) --> ~n

Iterates i from n*n-1 to zero. Prints a 1 if i%(n+1) is zero, otherwise 0. Then prints a newline if i%n=0 otherwise a space.

i;f(n){for(i=n*n;i--;)printf(i%n?"%d ":"%d\n",!(i%~n));}

i;f(n){for(i=n*n;i--;)printf("%d%c",!(i%~n),i%n?32:10);}

Level River St

Posted 2016-01-28T18:17:24.087

Reputation: 22 049

1n+1 is too dull. Use ~n instead! – anatolyg – 2016-01-29T00:23:05.577

Thanks! I should have spotted that, because it occured to me when I looked at NBZ's challenge today. – Level River St – 2016-01-29T00:31:15.273

I'm not too familiar with C. What does i; do? – Cyoce – 2016-08-20T22:56:44.440

@Cyoce i; just declares the variable i. In C you always have to declare a variable before using it, indicating the type so the compiler knows how much memory to allocate. With the GCC compiler, if you don't specify a type it is assumed to be int. – Level River St – 2016-08-21T00:55:07.133

@LevelRiverSt thanks. Since it didn't specify a type I was unsure if it was a declaration – Cyoce – 2016-08-21T01:28:16.147

1You can take 1 more byte off of the second one, since tabs are allowed, you can replace 32, with 9. – Bijan – 2017-03-29T22:40:57.597

5

K6, 1 byte

=

= is exactly this

Try it online!

Adám

Posted 2016-01-28T18:17:24.087

Reputation: 37 779

5

Mata, 4 bytes

I(3)

Output

[symmetric]
       1   2   3
    +-------------+
  1 |  1          |
  2 |  0   1      |
  3 |  0   0   1  |
    +-------------+

Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n*n

Guest0101

Posted 2016-01-28T18:17:24.087

Reputation: 51

5Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a good answer; (ab)use of built-ins is great for golfing. I noticed that your answer is actually 1 byte: I, and the other 3 bytes are just calling the function. That would make your answer one of the lowest on this challenge! :-) – wizzwizz4 – 2016-08-19T10:43:35.457

4

Brain-Flak, 206 170 162 bytes

(([{}])){({}<>(())<><(({})<{({}()(<>)<>)}{}>)>)}{}(({}<><(())>)){({}()<({[()]<({}()<({}<>((((()()()()){}){}){})((()()()()){}){})<>>)>}{})>)<>((()()()()()){})<>}<>

Try it online!

Post Rock Garf Hunter

Posted 2016-01-28T18:17:24.087

Reputation: 55 382

4

Japt, 14 12 10 bytes

Uo £Z®¥X|0

Test it online! Note: this version has a few extra bytes to pretty-print the output.

Uo £Z®¥X|0    // Implicit: U = input integer
Uo £          // Create the range [0..U). Map each item X and the full array Z to:
    Z®        //  Take the full array Z, and map each item Z to:
      ¥X|0    //   (X == Z) converted to a number. 1 for equal, 0 for non-equal.
              // Implicit: output result of last expression

ETHproductions

Posted 2016-01-28T18:17:24.087

Reputation: 47 880

4

Python 3.5 with NumPy - 57 49 30 bytes

import numpy
numpy.identity

NumPy.identity takes in an integer, n, and returns a n by n identity matrix. This answer is allowable via this policy.

linkian209

Posted 2016-01-28T18:17:24.087

Reputation: 51

4

Actually I believeimport numpy\nnumpy.identityis a legitimate answer.

– FryAmTheEggman – 2016-01-28T21:49:17.930

Thanks for the tip @MorganThrapp! And @FryAmTheEggman, you mean that my answer could just be import numpy\nnumpy.identity() which is 30 bytes? – linkian209 – 2016-01-29T20:09:14.590

I got so confused by \nnumpy lol... This would also be valid, @FryAmTheEggman, no? from numpy import identity. 26 bytes. – Ogaday – 2016-02-03T16:53:50.897

Also, see my answer something similar

– Ogaday – 2016-02-03T17:00:01.967

@Ogaday I don't think that is correct, the line you've given does not evaluate to a function. You would need to do from numpy import identidy\nidentity (in which case it would be shorter to use * instead of the specific builtin) – FryAmTheEggman – 2016-02-03T17:53:35.573

@FryAmTheEggman Ok, I see what you're getting at, in which case the solution would be from from numpy import*;identity at 27 bytes. According to the wording of the link, however, I think just importing satisfies the conditions: before the code is executed, there is no function "identity" in the scope, after execution there is. Think of importing as assignment: look at the language here and here: they both bind variables to names in the local scope.

– Ogaday – 2016-02-03T18:39:54.570

Similar to how s=sum is valid even though it doesn't evaluate to anything because it binds a value to new name in the local scope. I'm open to contradiction on this though, because the logical conclusion, therefore, is that from numpy import* is a valid solution, because it populates the namespace with all of the names from numpy... Which I don't think is a particularly satisfying solution. – Ogaday – 2016-02-03T18:42:41.823

@Ogaday The piece of code in the answer that is the actual function to be run (usually the last line) should evaluate to a function, and thus be assignable and callable. Simply importing a function doesn't result in a function object that can be assigned and called. – Mego – 2016-03-22T00:37:16.670

4

Pyth, 8 bytes

mmsqdkQQ

Try it here.

lirtosiast

Posted 2016-01-28T18:17:24.087

Reputation: 20 331

1I must say, it's highly unusual that the Pyth answer is four times longer than the shortest answer... – ETHproductions – 2016-01-28T21:01:00.260

Hrm, this was the best I was able to get that looks 100% valid, but I did find qRRQQ which seems to work except you get True and False instead of 1 and 0, however fixing this afaik requires using three bytes for sMM which doesn't help... – FryAmTheEggman – 2016-01-28T21:11:14.690

@FryAmTheEggman I also found qRRQQ. I've tried a number of other programs, and none of them were shorter. – lirtosiast – 2016-01-28T21:12:53.747

4

Mathematica, 35 Bytes

without using IdentityMatrix

Table[Boole[i==j],{i,1,#},{j,1,#}]&

A Simmons

Posted 2016-01-28T18:17:24.087

Reputation: 4 005

4

Javascript, 40

f=
n=>'0'.repeat(n).replace(/./g,"$`1$'\n")

I.oninput=_=>O.innerHTML=f(+I.value)
I.oninput()
<input id=I value=5>
<pre id=O>

Washington Guedes

Posted 2016-01-28T18:17:24.087

Reputation: 549

3

R, 50 bytes

f=function(n)matrix(c(1,rep(c(rep(0,n),1),n-1)),n)

Without using diag(), because I started coding without checking if there was a command for that... Also, I like my solution, despite being way too long.

Ivanneke

Posted 2016-01-28T18:17:24.087

Reputation: 121

36 bytes by abusing recycling (but gives a warning about non-multiple of length in recycling) – Giuseppe – 2018-01-15T19:32:02.830

3

Octave, 15 bytes

Because built-ins are no fun!

@(x)(k=1:x)==k'
@(x)~~diag(1:x)

Try it online!

The first one creates a vector from 1, 2, .. x, and compares it to itself transposed, expanding it to a square matrix where the diagonal elements are 1.

The second one creates a diagonal matrix with 1, 2, .. x is on the diagonal, then negates it twice, to get the diagonal equal 1, 1, .. 1.

Stewie Griffin

Posted 2016-01-28T18:17:24.087

Reputation: 43 471

3

Jolf, 7 + 1 = 8 bytes

Replace all ☺s with \x01 and \xad with a soft hyphen, or use the online interpreter. (Turn pretty output on for one byte.)

!☺!X\xad☺j
  !X       eye
    \xad☺   take one argument
         j  (the input)
!☺         get the data
           implicit printing

Probably more interesting, a solution without a builtin is 11 + 1 = 12 bytes

ZXZyjjdP=Sn
  Zyjj       create a matrix of width = height = j (input)
ZX    d      matrix map
        =Sn  if x-marker is y-marker
       P     as a number

Conor O'Brien

Posted 2016-01-28T18:17:24.087

Reputation: 36 228

3

JavaScript, 75 74 bytes

n=>eval("for(a=[],i=0;i<n;i++){a[i]=[];for(j=0;j<n;)a[i][j]=+(i==j++)};a")

Can be improved, probably.

If n=0 isn't necessary... 70 bytes

n=>eval("for(a=[i=0];i<n;i++)for(a[i]=[j=0];j<n;)a[i][j]=+(i==j++);a")

Conor O'Brien

Posted 2016-01-28T18:17:24.087

Reputation: 36 228

Since the zero by zero identity matrix is of questionable existence, a=[],i=0 could be golfed to a=[i=0]. – Jonathan Frech – 2018-08-28T16:59:40.420

I feel like one could argue that your other version also does not appropriately address n=0, since it outputs [], not [[]]; open for interpretation, though ... – Jonathan Frech – 2018-08-28T17:08:14.560

Based on this consensus, I think you could even drop the +(...).

– Jonathan Frech – 2018-08-28T17:12:56.467

@JonathanFrech True. this challenge predates that consensus tho – Conor O'Brien – 2018-08-28T17:40:55.837

3

K, 7 bytes

t=\:t:!

Take the equality cross product of two vectors containing [0,n).

In action:

  t=\:t:!3
(1 0 0
 0 1 0
 0 0 1)
  t=\:t:!5
(1 0 0 0 0
 0 1 0 0 0
 0 0 1 0 0
 0 0 0 1 0
 0 0 0 0 1)

JohnE

Posted 2016-01-28T18:17:24.087

Reputation: 4 632

3

Java, 60 bytes

n->{int[][]i=new int[n][n];for(;n-->0;)i[n][n]=1;return i;};

Creates a 2D array and replaces elements where row and column are equal with 1.

TNT

Posted 2016-01-28T18:17:24.087

Reputation: 2 442

You don't have to add the trailing semicolon to the byte-count for Java lambda answers. – Kevin Cruijssen – 2017-06-29T14:20:44.703

3

CJam, 7 bytes

{,_ff=}

This is a code block that pops an integer from the stack and pushes a 2D array in return.

Try it online!

Dennis

Posted 2016-01-28T18:17:24.087

Reputation: 196 637

3

Perl, 39 33 bytes

/$/,say map$`==$_|0,@%for@%=1..<>

Thanks to Ton Hospel for saving 6 bytes

Running with the -E perlrun:

$ echo 3 | perl -E'@%=1..<>;$a=$_,say map{$a==$_|0}@%for@%'
100
010
001

andlrc

Posted 2016-01-28T18:17:24.087

Reputation: 1 613

Golfing a bit more: /$/,say map$`==$_|0,@%for@%=1..<> or even better //,say map$'==$_|0,@%for@%=1..<> but like that you can't put it in single quotes anymore – Ton Hospel – 2016-03-08T15:51:04.623

@TonHospel Wow thats cool, thanks. The later would require the use of print instead of say, because -E is only free on the command line. – andlrc – 2016-03-14T22:15:46.920

3

Mathematica, 14 bytes

IdentityMatrix

Test case

IdentityMatrix[4]
(* {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} *)

njpipeorgan

Posted 2016-01-28T18:17:24.087

Reputation: 2 992

2

Rust, 59 bytes

|n|{let mut l=vec![vec![0;n];n];for i in 0..n{l[i][i]=1};l}

Defines an anonymous function, creates a vector of vectors of the specified length, sets the diagonals to 1 and returns it. Boring, but shorter than any iterator-based approaches due to .collect overhead.

Alternatively, if returning an iterator of iterators is allowed it can be done in 44 characters:

|n|(0..n).map(|i|(0..n).map(|j|(j==i)as u8))

CensoredUsername

Posted 2016-01-28T18:17:24.087

Reputation: 951

2

Matlab, 3 bytes

eye

Does exactly this. eye(n) for an n-by-n matrix.

and also one without eye, 15 bytes:

diag(ones(1,n))

EBH

Posted 2016-01-28T18:17:24.087

Reputation: 221

2

R, 32 31 bytes

function(n)+outer(1:n,1:n,"==")

Try it online!

Thanks to Kirill L. for -1 byte

Alternative to Ivanneke's solution, but obviously far longer than just plain old diag.

Giuseppe

Posted 2016-01-28T18:17:24.087

Reputation: 21 077

You can swap *1 for +: 31 bytes

– Kirill L. – 2018-04-26T18:48:59.213

@KirillL. ah, yes, thank you. – Giuseppe – 2018-04-26T20:40:56.110

2

R, 28 bytes

function(n,x=1:n)+!x%o%x-x^2

Try it online!

For pure fun, just another attempt at a non-built-in R solution. Uses the shortcut %o% version of the outer function.

Kirill L.

Posted 2016-01-28T18:17:24.087

Reputation: 6 693

2

05AB1E, 4 bytes

°¨œÙ

Try it online!

Unique permutations of (10^input)[0:-1]

Kaldo

Posted 2016-01-28T18:17:24.087

Reputation: 1 135

2Nice answer! An alternative is LDδQ, for 4 bytes as well. – Mr. Xcoder – 2018-08-28T15:16:44.513

@Mr.Xcoder First time I see δ being used. Nice approach as well! – Kevin Cruijssen – 2018-08-28T15:25:41.643

2

PowerShell, 52 bytes

param($a)1..$a|%{$d++;(1..$a|%{+($d-eq$_)})-join' '}

Since the only built-in .NET class for matrices is ... umm ... inadequate, shall we say, we're just going to construct and output a string representation here...

Takes input $a then executes a double-for-loop over range 1..$a. Each outer loop we increment helper variable $d (the first loop, since $d isn't initialized, turns $d++ into $null + 1 = 1 ... in PowerShell logic it makes sense), and each inner loop is simply an integer-cast with + of an equality between $d and the current element $_. Each inner loop is -joined together with spaces so it prints nicely, and each outer loop causes a newline, so output code is pretty cheap.

Example

PS C:\Tools\Scripts\golfing> .\construct-identity-matrix.ps1 10
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

AdmBorkBork

Posted 2016-01-28T18:17:24.087

Reputation: 41 581

2

Haskell, 27 bytes

import Data.Matrix
identity

Maybe a little bit boring.

Usage example:

Prelude Data.Matrix> identity 4
( 1 0 0 0 )
( 0 1 0 0 )
( 0 0 1 0 )
( 0 0 0 1 )

nimi

Posted 2016-01-28T18:17:24.087

Reputation: 34 639

2

Ruby, 56 48 bytes

->n{(([1]+[0]*n)*(n-1)+[1]).each_slice(n).to_a}

Explanation:

Concatenates n - 1 sequences of 1 followed by n 0s into an array, and appends 1 to the end. Then slices the result into n arrays of length n and evaluates to an array having the slices as its elements.

Per Alex A., shaved 8 bytes by putting it in the form of a lambda.

PellMell

Posted 2016-01-28T18:17:24.087

Reputation: 171

2

Ruby,38 bytes

Returns a 2D array.

->n{(0..n-1).map{|i|s=[0]*n;s[i]=1;s}}

Iterates through each row of the array. For each iteration generates a row of n zeros, then changes one of them to a 1

Usage

f=->n{(0..n-1).map{|i|s=[0]*n;s[i]=1;s}}
p f[5]

[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

A different approach (string):

Ruby, 47 bytes

->n{(0..n-1).map{|i|s='0 '*n;s[i*2]=?1;puts s}}

for each row, makes a string of '0 'repeated n times, changes one of the 0s to 1, and prints it

Level River St

Posted 2016-01-28T18:17:24.087

Reputation: 22 049

(0...n) is equivalent to (0..n-1). – Value Ink – 2017-06-22T20:43:02.023

2

PARI/GP, 11 5 bytes

matid

is sufficient, or

n->matid(n)

(11 bytes) as a 'roll-your-own' closure. If you want to work entirely by hand,

n->matrix(n,n,i,j,i==j)

(23 bytes) should suffice.

Charles

Posted 2016-01-28T18:17:24.087

Reputation: 2 435

2

Perl, 31 24 bytes

Includes +3 for -p (code contains ' so I can't just use the implied -e)

Run with the count on STDIN, e.g.

./diagonal.pl <<< 3

Outputs:

100
010
001

diagonal.pl:

#!/usr/bin/perl -p
$_=0 x$_;s/./$`1$'
/g

Ton Hospel

Posted 2016-01-28T18:17:24.087

Reputation: 14 114

1

PHP, 64 bytes

for(;$i<$argn**2;$m?:$k++)echo$k==$m?:0,($m=++$i%$argn)?" ":"
";

Try it online!

Jörg Hülsermann

Posted 2016-01-28T18:17:24.087

Reputation: 13 026

1

Jelly, 2 bytes

Try it online!

scatter

Posted 2016-01-28T18:17:24.087

Reputation: 874

1

tinylisp repl, 107 bytes

(d =(q((A R C S)(i C(=(c(e R C)A)R(s C 1)S)A
(d #(q((A R S)(i R(#(c(=()R S S)A)(s R 1)S)A
(d f(q((S)(#()S S

Using the repl saves 6 bytes in implied closing parentheses at the ends of lines. Defines a function f which takes a positive integer and returns the identity matrix of that size as a nested list. Try it online!

Explanation

The function = constructs a row in the matrix. Its arguments are (in order) an Accumulator, the Row number, the current Column number, and the Size of the matrix. If the column is not zero (i C ...), then cons a number to the accumulator (1 if the row and column are equal, 0 otherwise) (c (e R C) A), decrease the column number (s C 1), and recurse (= ...). Otherwise, return the accumulator A.

The function # constructs the matrix as a list of rows. Its arguments are an Accumulator, the current Row number, and the Size of the matrix. If the row number is not zero (i R ...), then generate a row (=()R S S) and cons it to the accumulator (c ... A), decrease the row number (s R 1), and recurse (# ...). Otherwise, return the accumulator A.

Finally, the function f is simply a single-argument wrapper function that calls #.

DLosc

Posted 2016-01-28T18:17:24.087

Reputation: 21 213

1

Clojure, 45 bytes

#(for[i(range %)](assoc(vec(repeat % 0))i 1))

NikoNyrh

Posted 2016-01-28T18:17:24.087

Reputation: 2 361

1

PHP, 49 bytes

function($n){for(;$n--;)$k[$n][$n]=1;return $k;};

There is a bit of a caveat with this answer, and I will delete it or mark it as non-competing if it is deemed invalid.

The array returned by this function technically only has n elements, those being a 1 at every intersection. ie: 0:0 1:1, 2:2, etc

However, not only does this satisfy the definition of the identity matrix as given by the question:

The identity matrix is one that has 1s spanning from the top left down to the bottom right

It also works if used as an identity matrix, as an empty value in an array in PHP is treated as 0 if used arithmetically.

Xanderhall

Posted 2016-01-28T18:17:24.087

Reputation: 1 236

1

Axiom, 68 bytes

f(n:PI):Matrix INT==matrix([[(i=j=>1;0)for i in 1..n]for j in 1..n])

test and results

(30) -> for i in 1..3 repeat output f(i)
   [1]
   +1  0+
   |    |
   +0  1+
   +1  0  0+
   |       |
   |0  1  0|
   |       |
   +0  0  1+
                                                               Type: Void

RosLuP

Posted 2016-01-28T18:17:24.087

Reputation: 3 036

1

Python 2, 52 bytes

y=x=2**input()
while~-x:x/=2;print str(bin(y+x))[3:]

Try it online!

Using binary representation of powers of 2.

mdahmoune

Posted 2016-01-28T18:17:24.087

Reputation: 2 605

1

Mathematica ,26 bytes

without using IdentityMatrix

Boole[#==#2]&~Array~{#,#}&

J42161217

Posted 2016-01-28T18:17:24.087

Reputation: 15 931

1

PowerShell, 45 bytes

{param($n)0..--$n|%{"$(,0*$_+1+,0*($n-$_))"}}

Try It Online!

Andrei Odegov

Posted 2016-01-28T18:17:24.087

Reputation: 939

1

Excel VBA, 55 52 43 Bytes

Anonymous VBE immediate window function that takes input as number from cell [A1] and outputs the identity matrix to the range of [A1].Resize(n,n)

[A1].Resize([A1],[A1])="=1*(Row()=Column())

-2 bytes thanks to Engineer Toast

Previous Version

n=[A1]:[A1].Resize(n,n)=0:For i=1To n:Cells(i,i)=1:Next

Taylor Scott

Posted 2016-01-28T18:17:24.087

Reputation: 6 709

1Save 1 byte: "=1*(Row()=Column())" – Engineer Toast – 2018-04-25T15:18:00.833

1

Bash (w/ coreutils and awk), 51 50 bytes

yes 0|head -$((N*N))|xargs -n$N echo|awk {\$NR=1}1

Usage

Set the N environment variable to the matrix size

$ N=5
$ yes 0|head -$((N*N))|xargs -n$N echo|awk {\$NR=1}1
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

Explanation

  • yes 0 generates an endless stream of 0s to stdout;
  • head -$((N*N)) takes the first N2 lines;
  • xargs -n$N echo groups every N lines and outputs them together;
  • awk {\$NR=1}1 changes the value of the field whose index matches the line number to a 1 (otherwise it remains 0) and then outputs the whole record.

There may be a shorter way to generate N2 lines of 0s, but I haven't found one yet...

Xophmeister

Posted 2016-01-28T18:17:24.087

Reputation: 111

1

Vim, 47 keystrokes

"zy$␘a@q␛"xYoa␛"zPy$qqo␛@"0␛q@x3Gqqr1jlq@x1G2dd

is CtrlX and is Esc

Explanation

"zy$␘           Save n for use later
a@q␛"xY         Create the macro `x` that repeats the macro `q` n-1 times
oa␛"zPy$        Create an anonymous macro that inserts a character n times
qqo␛@"0␛q@x    Create the macro `q` that adds a new line with n zeroes and run it n times
3G               Go to the top-left corner of the matrix
qqr1jlq@x        Redefine `q` as a macro that replaces the character at the cursor with
                   a one and moves the cursor one step down-right. Run `q` n times
1G2dd            Delete the two lines used in macro defenitions

Herman L

Posted 2016-01-28T18:17:24.087

Reputation: 3 611

1

Tcl, 92 bytes

proc I n {time {incr j;set a "";set i 0;time {lappend a [expr [incr i]==$j]} $n;puts $a} $n}

Try it online!

sergiol

Posted 2016-01-28T18:17:24.087

Reputation: 3 055

1

Husk, 4 bytes

´Ṫ=ḣ

Try it online!

Explanation

´Ṫ=ḣ  -- example input: 2
   ḣ  -- range: [1,2]
´     -- duplicate argument: [1,2] [1,2]
 Ṫ    -- outer product by
  =   -- | equality: [[1==1,1==2],[2==1,2==2]]
      -- : [[1,0],[0,1]]

ბიმო

Posted 2016-01-28T18:17:24.087

Reputation: 15 345

1

Gol><>, 10 bytes

IR0PlF}D|;

Try it online!

The output for n = 5 looks like this:

[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]

How it works

IR0PlF}D|;

IR0P       Take input n, then fill the stack with that many 0s
           and then make the top 1; stack = [0 ... 0 1]
    lF..|  Do the following n times...
      }D   Rotate the stack once to the right, and print the whole stack
         ; Terminate

Bubbler

Posted 2016-01-28T18:17:24.087

Reputation: 16 616

1

05AB1E, 6 bytes

Lã€Ësô

Try it online.

Explanation:

L         # List in range [1,n]
          #  i.e. 3 → [1,2,3]
 ã        # Cartesian power of this list
          #  i.e. [1,2,3] → [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
  €Ë      # Check for every pair if they are equal or not
          #  i.e. [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
          #   → [1,0,0,0,1,0,0,0,1]
    sô    # Split it into parts equal to the input
          #  i.e. [1,0,0,0,1,0,0,0,1] and 3 → [[1,0,0],[0,1,0],[0,0,1]]

Kevin Cruijssen

Posted 2016-01-28T18:17:24.087

Reputation: 67 575

1

Alternative 6-byter °¨IF=Á

– Kaldo – 2018-08-28T15:01:52.770

@Kaldo Ah, that's quite a bit different than my approach, but also pretty cool. And I just saw your 4-byte answer, +1 from me. :) – Kevin Cruijssen – 2018-08-28T15:22:17.770

1

Perl 6,  41 37  35 bytes

{$/=1..$_;$/.map: {$/.map: {+($^a==$_)}}} # 41 bytes
{$/=1..$_;$/.map: {$/.map: +(*==$_)}}     # 37 bytes
{$_=1..$^a;.map: {.map: +(*==$^a)}}       # 35 bytes

This outputs a list of lists.

Usage:

# give it a lexical name
my &identity-matrix = {…}

# format it so that it is readable
sub readable ( @_ ) { @_.join: "\n" }

say readable identity-matrix 10
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

Brad Gilbert b2gills

Posted 2016-01-28T18:17:24.087

Reputation: 12 713

1

, 3 chars / 6 bytes

Мƕï

Try it here (Firefox only).

I'm finding a lot of these 3-char solutions. It's just a builtin.

Bonus solution, 11 chars / 22 bytes

⩥ïⓜãĉ⇝+($≔a

Try it here (Firefox only).

The code in the interpreter link uses some more bytes to pretty-print output.

Explanation

⩥ïⓜãĉ⇝+($≔a // implicit: ï=input
⩥ïⓜ         // create a range [0,ï) and map over it
    ãĉ⇝      // get a copy of range ã and map over it
       +($≔a // output 1 or 0 depending on whether item in first map == item in current map
             // implicit output

Mama Fun Roll

Posted 2016-01-28T18:17:24.087

Reputation: 7 234

How does this work? – lirtosiast – 2016-01-29T03:24:40.213

It's just a builtin. I'll post a bonus solution soon. – Mama Fun Roll – 2016-01-29T03:28:24.920

Alright, updated. – Mama Fun Roll – 2016-01-29T03:47:22.393

1

Scala, 53 51 bytes

(n:Int)=>Seq.tabulate(n,n){(i,j)=>if(i==j)1 else 0}

Jacob

Posted 2016-01-28T18:17:24.087

Reputation: 1 582

I am unfamiliar with Scala, though is the space in 1 else necessary? – Jonathan Frech – 2018-08-28T17:48:58.823

@JonathanFrech yes, it actually won’t compile without it, with “Invalid literal number” message. Thanks anyway! And you should learn Scala, it is beautiful. – Jacob – 2018-08-28T17:53:12.707

1

Samau, 5 bytes

,;`=o

It's a function that takes a number and return a 2D array.

,;`=o
,      range from 0 to n-1
 ;     duplicate
    o  take the outer product by
  `=   equality

alephalpha

Posted 2016-01-28T18:17:24.087

Reputation: 23 988

1

Mouse, 75 bytes

N:1I:(I.N.1+<^1J:(J.I.<^0!32!'1J.+J:)1!32!'(J.N.<^0!32!'1J.+J:)10!'1I.+I:)$

This is a full program that reads from STDIN and prints to STDOUT. Each line will have a single trailing space and there will be one trailing newline at the end of the output.

Explanation:

~ Read N from STDIN
? N:

~ Initialize a row index
1 I:

~ Loop while we've printed fewer than N+1 rows
( I. N. 1 + < ^

  ~ Initialize a column index
  1 J:

  ~ Print I-1 space-separated zeros
  ( J. I. < ^
    0 !
    32 !'
    1 J. + J:
  )

  ~ Print 1 and a space
  1 !
  32 !'

  ~ Print the remaining zeros
  ( J. N. < ^
    0 !
    32 !'
    1 J. + J:
  )

  ~ Newline
  10 !'

  ~ Increment the row index
  1 I. + I:
)
$

Alex A.

Posted 2016-01-28T18:17:24.087

Reputation: 23 761

1

Java, 200 Bytes

This is the shortest working java code i could come up with. Nothing to special ;)

class a{public static void main(String[]a){int c=Integer.parseInt(a[0]);int[][]b=new int[c][c];for(int d=0;d<c;d++){for(int e=0;e<c;e++){b[d][d]=1;System.out.print(b[d][e]);}System.out.println();}}}

Partly posting this hoping someone could explain why TNT 's answer is valid (it has no class declaration and no main(String[] args))? I'm new to code golf and i thought that answers had to be a working program?

SoloKix

Posted 2016-01-28T18:17:24.087

Reputation: 89

The answer in question is a function, which is a valid submission by our rules. You can make this shorter by changing class to interface, which allows you to drop the public. – Mego – 2016-03-22T00:39:25.910

1

Python 3, 22 bytes

from numpy import*;eye

It's a bit boring, but it's short! Because of discussion on meta, I think this follows the spirit of the rules a bit more closely.

Ogaday

Posted 2016-01-28T18:17:24.087

Reputation: 471

1I'm unsure about your points, why don't you try adding an answer to the meta question, so it can get feedback from more people? The main thing that bothers me about it is the arguments against the empty file being valid, because then you could write a library that defined all functions to make all your answers extremely small. But I'm uncertain of how to differentiate between import and def now that you've brought it up. – FryAmTheEggman – 2016-02-03T18:55:57.943

@FryAmTheEggman +1 I'll open it to the floor. – Ogaday – 2016-02-03T19:01:02.437

1

Ruby 42 bytes

->n{([1]+[0]*(n-1)).permutation.to_a.uniq}

creates every permutation of the array [1,0,0,0...] and then takes the unique ones. this will end up with the ones we want, in the correct order.

MegaTom

Posted 2016-01-28T18:17:24.087

Reputation: 3 787

1

C++, 111 bytes

I love abusing for loops.

#include <stdio.h>
void f(int n){for(int j,i=0;i++<n;putchar(10))for(j=0;j++<n;putchar(32))putchar(i-j?48:49);}

MegaTom

Posted 2016-01-28T18:17:24.087

Reputation: 3 787

1

Oracle SQL 11.2, 102 bytes

SELECT SUBSTR(RPAD(0,:1,0),:1-LEVEL+2)||1||SUBSTR(RPAD(0,:1,0),LEVEL+1)FROM DUAL CONNECT BY LEVEL<=:1;

Jeto

Posted 2016-01-28T18:17:24.087

Reputation: 1 601

1

Python 3, 116 107 characters

def M(n):
 x=[]
 for i in range(n):
  r=[]
  for j in range(n):
   r+=[1 if i==j else 0]
  x+=[r]
 return x

Output

iM(1) 
[[1]]
iM(2)
[[1, 0], [0, 1]]
iM(3)

Argenis García

Posted 2016-01-28T18:17:24.087

Reputation: 223

r.append(i) is the same as r+=[i] i think – Seadrus – 2016-02-09T23:27:52.107

There's a lot of further golfing that can be done here – Mego – 2016-03-22T00:40:02.417

Yeah, 1 if i==j else 0 can be int(i==j). – Zacharý – 2017-06-29T20:03:25.723

58 bytes – hakr14 – 2018-04-25T19:13:46.170

1

Jellyfish, 12 bytes

P`N(Rri
   -

Try it online! This entry is non-competing.

Explanation

  • i is input, and r computes the range from 0 to input-1.
  • The operator ( is a left hook. On inputs - and R, it applies R (rotate) to the range and its negated version. This gives the i×i matrix whose rows are the ranges ri, rotated k steps to the right for each row k.
  • `N computes the logical negation of each entry: 0 goes to 1 and everything else to 0. Since the 0s are on the diagonal, this gives the identity matrix.
  • P prints the matrix.

Zgarb

Posted 2016-01-28T18:17:24.087

Reputation: 39 083

1

picTuring - 16 States (320 bytes)

I thought this challenge might be a good chance to show off my new Turing Machine interpreter.

0 * 0 * r
0 _ 1 * r
1 * 2 1 l
2 * 2 * l
2 _ d * l
d _ f * r
d 0 d 1 l
d 1 p 0 r
p * p * r
p _ q * r
q * q * r
q _ 2 0 l
f * f _ r
f _ g * r
g 1 g _ r
g 0 r 1 r
r * r * l
r _ c * r
c _ n * d
c 0 o * d
c 1 i * d
o * e 0 u
i * j 0 r
j * h 1 u
h * k * r
k _ halt * *
k * c * *
e * c * r
n * r * l

The input must be in binary (1 / 0), with the number terminating at the head (the white circle).

How to Run it:

In case you didn't realize that the link in the header leads to my interpreter, you can find it here -> http://fred-choi.com/projects/picTuring/index.html

Here is the compressed test case (since my interpreter does not support permalinks yet):

AwAlH0QRhBaGLTgJjCSMg AwAgVCoQTgUKB9EBGcI6ogJhSANrDtmgTkgCYmyyVIBmaclolqBrIADpOtdxP17ckAR0awxESbzFIcoArAYQGSOKpABzcbG2pta3T2i44sEzComkAYx12kAOzTlYd0AHsXb3AEtvsF4QAKY8AK7U-hAAVsawsRAAFrgRyRAA1uKZSIkAhngALmhgsJkQdhAlsKHlOs6WEHhAA

To use it, just hover over save, paste the compressed code in the text box, and click load.

loading

To edit the tape, make sure you're in "Type" mode (Edit -> Paint), then double click the tape, and a red box should show up, indicating that you're now editing the tape.

Once you're finished, hit Edit -> Ok to save the tape, then Controls -> Run. Controls -> Reset will restore the tape to when you hit Edit -> Ok.

Again, this is interpreter is still indev, I don't have a manual yet, so feel free to leave comments if I left anything out.

KoreanwGlasses

Posted 2016-01-28T18:17:24.087

Reputation: 888

1

PHP, 106 bytes

<?php $i=$argv[1];for($j=0;$j<$i;$j++){for($h=0;$h<$i;$h++){$l="0 ";if($h==$j)$l="1 ";echo$l;}echo"\n";}?>

Based on a double for loop, it uses the command-line argument for the input.

php 70365.php 3
1 0 0 
0 1 0 
0 0 1

Expanded code:

<?php
    $i = $argv[1];
    for($j = 0; $j < $i; $j++)
    {
        for($h = 0; $h < $i; $h++)
        {
            $l="0 ";
            if($h == $j)
                $l="1 ";
            echo $l;
        }
        echo "\n";
    }
?>

Kees

Posted 2016-01-28T18:17:24.087

Reputation: 41

0

V, 16, 11 bytes (non-competing?)

Ài0 ÀÄòjl

Try it online!

James

Posted 2016-01-28T18:17:24.087

Reputation: 54 537

0

Common Lisp, 96 94 92 bytes

(lambda(n)(set'a(make-array(list n n):initial-element 0))(dotimes(i n)(setf(aref a i i)1))a)

Try it online!

ceilingcat

Posted 2016-01-28T18:17:24.087

Reputation: 5 503

0

PHP, 55 bytes

while($p**.5<$z=+$argn)echo$p%-~$z?0:1,"
 "[++$p%$z>0];

requires PHP 5.6 or later for the power operator. Note that the second line begins with a space!

Run as pipe with -nR or try it online.

Titus

Posted 2016-01-28T18:17:24.087

Reputation: 13 814

0

Charcoal, 7 bytes

EθEθ⁼κμ

Try it online!

This returns an array, which in Charcoal is not readable in its default format. A version using Wolfram Lists is included below for readability.

Explanation

Eθ       Map for each number from 0 to first input
   Eθ    Map for each number from 0 to first input
      ⁼κμ Return whether both loop indices (yes, indices) are the same. The variables here are: i = first loop variable, k = first loop index, l = second loop variable, m = second loop index.

Readable version
Even accepts input as unary :P

ASCII-only

Posted 2016-01-28T18:17:24.087

Reputation: 4 687

0

PHP 88 Bytes

Try it online

Code

<?php for($i=0;$i++<$argv;){$a=array_fill(1,$argv,0);$a[$i]=1;echo implode(",",$a)."
";}

Explanation

<?php 
  for($i=0;$i++<$argv;){          // loop up to the argument
      $a=array_fill(1,$argv,0);   // create an array fill with 0 with length = $argv value
      $a[$i]=1;                   // use the current iteration to place the "1"
      echo implode(",",$a)."      // implode to output the matrix
     ";}

Output

  $argv=5

  1,0,0,0,0
  0,1,0,0,0
  0,0,1,0,0
  0,0,0,1,0
  0,0,0,0,1

Francisco Hahn

Posted 2016-01-28T18:17:24.087

Reputation: 591

0

Forth (gforth), 48 bytes

: f dup 0 do dup 0 do 0 i j = - . loop cr loop ;

Try it online!

Explanation

uses nested loops to output the matrix. For each element it outputs 1 if the indexes are equal, and 0 otherwise.

Code Explanation

:f           \ start a new word definition
  dup        \ duplicate input
  0 do       \ outer counted loop from 0 to input - 1
    dup      \ duplicate input again 
    0 do     \ inner counted loop from 0 to input - 1
      0      \ put a 0 on the stack (used to convert -1 to 1)
      i j =  \ -1 if i equals j, 0 otherwise
      - .    \ subtract from 0 to convert -1 to 1, and output
    loop     \ end inner loop
    cr       \ output a newline
  loop       \ end outer loop
;            \ end word definition

reffu

Posted 2016-01-28T18:17:24.087

Reputation: 1 361

0

D, 114 bytes

void f(int n){import std.stdio;int N=n*n;while(N--){if(N%(n+1))write("0 ");else write("1 ");if(N%n==0)writeln();}}

Try it online!

mdahmoune

Posted 2016-01-28T18:17:24.087

Reputation: 2 605

0

Seriously, 24 bytes

,;╗r`╙k╜#"{:0%sb}"%f#`MR

Try it online!

Explanation:

,;╗r`╙k╜#"{:0%sb}"%f#`MR
,;╗                       get input (n), save a copy in register 0
   r                      push [0..n-1]
    `                `M   map the function:
     ╙k                     push [2**a]
       ╜#"{:0%sb}"%         push "{:0nb}"
                   f#       format and explode string
                            (push binary representation, padded with zeroes to n digits)
                       R  reverse list

Mego

Posted 2016-01-28T18:17:24.087

Reputation: 32 998

0

Sage, 15 bytes

identity_matrix

Exactly what it says on the tin

Try it online

Thanks to Lynn for pointing out that I was being a doofus.

Mego

Posted 2016-01-28T18:17:24.087

Reputation: 32 998

Why not eta-reduce this to identity_matrix? – Lynn – 2016-08-21T18:21:08.773