Why aren't sparse matrices padded with zeros to the highest sizes?

4 views (last 30 days)
The following code
A = sparse(1:3, 1:3, 1:3)
B = sparse(4,4,4)
A+B
gives the error
Error using +
Matrix dimensions must agree.
because the matrices have different sizes:
size(A) % returns ans = [3 3]
size(B) % returns ans = [4 4]
why aren't sparse matrices zero padded to the highest dimension in order to naturally allow for operations such as A+B ?
In my (beginner) understanding, I don't see any difference in sparse(1:3, 1:3, 1:3), sparse(1:3, 1:3, 1:3, 4, 4) or sparse(1:3, 1:3, 1:3, 100, 100), but apparently they differ in sizes. Which details am I missing? Where do I find them in the documentation?

Answers (2)

Guillaume
Guillaume on 7 Dec 2018
sparse is just a method for efficiently storing matrices that contain lots of zeros. It doesn't change the fact that matrices have a fixed size and it doesn't change the mathematics that adding two differently sized matrices is undefined.
apparently they differ in sizes
Well, yes, as documented:
  • S = sparse(i,j,v) generates a sparse matrix S from the triplets i, j, and v [..] The max(i)-by-max(j) output matrix
This applies to your sparse(1:3, 1:3, 1:3), so the matrix is 3x3
  • S = sparse(i,j,v,m,n) specifies the size of S as m-by-n.
This applies to all your other examples, where the matrix is exactly the size you specify (4x4, 100x100)
You can't add a 3x3 full matrix with a 4x4 full matrix. The mathematics don't change with sparse.
  6 Comments
Stephen23
Stephen23 on 7 Dec 2018
Edited: Stephen23 on 7 Dec 2018
'note: technically 1x1 matrix and scalar are different "objects" '
MATLAB does not have a "scalar" numeric class, all scalars are 1x1x1x1x... arrays:

Sign in to comment.


Bruno Luong
Bruno Luong on 7 Dec 2018
Edited: Bruno Luong on 7 Dec 2018
Not specific to sparse, similar such operator on full matrices also returns error.
A sparse matrix is designed to be equivalent to a full matrix with the same size, just the internal storage is different.
You can only add/substract matrix/array with the same sizes.
Exception is auto-expansion of "singleton" dimension(s).
That the way it is, if you want to add, you have to do your own padding first. And IMO this is a good design to avoid user doing stupid things.

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Tags

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!