Spring 2006
Defining a big (but sparse) matrix in Matlab or Scilab
For your project, you may have to define a large matrix in Matlab
or Scilab, and most of the entries in this matrix will probably
be zero.
Here is a convenient way to do this that works in both Matlab and Scilab.
Suppose you want to enter the following 10x10 matrix:
| 0 | 0 | 0 | 0 | 0 | 1 | 2 | 5 | 3.1 | 2.2 |
| 0.5 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0.6 | 0.45 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0.95 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0.95 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0.95 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0.95 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | 0 |
First, use the zeros function to create a matrix of all zeros.
(Note the semi-colon at the end of the command. Without this, the matrix will be printed after you
hit Enter.)
-->A = zeros(10,10);
Now we fill in only the non-zero entries:
-->A(1,6) = 1;
-->A(1,7) = 2;
-->A(1,8) = 5;
-->A(1,9) = 3.1;
-->A(1,10) = 2.2;
-->A(2,1) = 0.5;
-->A(2,2) = 0.25;
and so on until
-->A(10,9) = 0.95;
For a large matrix that is mostly zeros, this can save quite a bit of typing.