2
votes

I read interesting article about correct memory usage in MATLAB. Here it is: Link at official website And here I see example:

If your data contains many zeros, consider using sparse arrays, which store only nonzero elements. The following example compares the space required for storage of an array of mainly zeros:

A = diag(1e3,1e3);    % Full matrix with ones on the diagonal
As = sparse(A)        % Sparse matrix with only nonzero elements

I tried to implement it in my code and find interesting moment: A = diag(1e3,1e3) does not create matrix with ones on the diagonal! It creates matrix of zeros with only one nonzero element:

clear A
A = diag(1e3,1e3);
find(A);
ans =
     1001001

A(1001001)
ans =
        1000

Ok. I read about diag function in help and see this:

D = diag(v) returns a square diagonal matrix with the elements of vector v on the main diagonal.

Ok! So it really doesn't create diagonal matrix if v consist of 1 element! Is it mistake at help? BUT. One more question: why it works this way?

diag(5,5)
ans =
     0     0     0     0     0     5
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0

I expect to get matrix 5x5 with 5 value at (1,1) or (5,5). Why it creates 6x6 matrix and why 5 is a (1,6) element?


Some time ago they fix documentation: enter image description here

3

3 Answers

3
votes

Manual: diag you are using the 2nd overloaded version of diag:

D = diag(v,k) places the elements of vector v on the kth diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.

So your command A = diag(5,5) will construct a matrix where the diagonal elements of 5th diagonal above the main diagonal will be equal to the vector [5]. Thus the resulting value where only A(1,6) has a value.

If you want to have a 1e3x1e3 Matrix with ones on the diagonal try

A = diag(ones(1,1e3));
2
votes

The article is incorrect.

A = diag(1e3,1e3);

does not produce a matrix with ones on the diagonal. The code should instead read:

A = eye(1e3,1e3);
1
votes

Now reading your question again, I understood it really and have to rewrite my answer. You are refering to this part of the documentation:

A = diag(1e3,1e3);    % Full matrix with ones on the diagonal
As = sparse(A)        % Sparse matrix with only nonzero elements
whos
  Name      Size                  Bytes  Class

  A      1001x1001                8016008  double array
  As     1001x1001                4020     double array (sparse)

That example is definitely wrong, probably it should be:

A=eye(1e3,1e3)
As=sparse(A);

Which creates a 1000x1000 matrix with ones on the main diagonal.

The bug is reported to mathworks