-12

Write a function called identity that creates a square identity matrix, which is a matrix whose elements are 0 except for the elements on the diagonal (from top left to bottom right) which have a value of 1. The diagonal consists of those elements whose row and column indexes are the same: (1,1), (2,2), etc.

The function takes one positive integer input argument, which is the size of the matrix, and returns the matrix itself as an output argument.

For example, identity(4) must return a 4-by-4 identity matrix.

You are not allowed to use the built-in eye or diag functions.

(Hint: you can index into a matrix with a single index and MATLAB will handle it as if it was a vector using column-major order.)

Amro
  • 123,847
  • 25
  • 243
  • 454
yasaman
  • 9
  • 1
  • 6
    This is easy to achieve and sounds like homework. Where is your research effort? Please read [how to ask](http://stackoverflow.com/help/how-to-ask) and edit your question after. Show what you have tried so far and what your thoughts are to solve this problem. – Matt Jul 28 '15 at 07:18
  • Or you can do like this `fix(corrcoef(rand(10,10)))` :) It is not a good way, but it will do what you need. – patrik Jul 28 '15 at 11:51

3 Answers3

2

Let's do it in two simple lines and without zeros... The first line creates a n x n matrix where all elements are 0. After you can (as your hint says) address the elements with a single argument. The distance between the ones in the identity matrix are n+1. This way you write the ones with the mentioned distance until the end.

function out = identity(n)
    out(n,n)       = 0;
    out(1:n+1:end) = 1;
end
Matt
  • 12,848
  • 2
  • 31
  • 53
  • Do you know, if there is a performance difference between `A(n,n)=0` and `A=zeros(n)`? – Thomas Jul 28 '15 at 11:13
  • Oh wow, I just tested this, and for `N=10000`, your approach takes 0.000255 seconds, while `zeros(N)` takes 1.106566 seconds. I always thought, that the standard way was to use `zeros(N)`. – Thomas Jul 28 '15 at 11:17
  • @sonystarmap Check out [this](http://undocumentedmatlab.com/blog/preallocation-performance) article on Undocumented Matlab. Don't miss the section «Variants for pre-allocation». – Matt Jul 28 '15 at 11:44
1

You could start with the basics:

function M = identity(n)
    M = zeros(n);
    for i=1:n
        M(i,i) = 1;
    end
end

Pretty much the same code as any other language...

Amro
  • 123,847
  • 25
  • 243
  • 454
0

Assuming that you can use the built-in function zeros(), a possible implementation of the eye() funtion is the following one:

function matrix = identity(n)
    out = zeros(n);
    idx = 1:n+1:n^2;
    out(idx) = 1;
    matrix = out;
end
josoler
  • 1,393
  • 9
  • 15