Arguments Matter
Calling Matlab's ones()
or zeros()
or magic()
with a single argument n
, creates a square matrix with size n-by-n
:
>> a = ones(5)
a = 1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Calling the same functions with 2 arguments (r, c)
instead creates a matrix of size r-by-c
:
>> a = ones(2, 5)
a = 1 1 1 1 1
1 1 1 1 1
This is all well documented in Matlab's documentation.
Size Matters Too
Doubles
Having said this, when you do a = zeros(1e6)
you are creating a square matrix of size 1e6 * 1e6 = 1e12
. Since these are doubles the total allocated size would be 8 * 1e12 Bytes
which is circa (8 * 1e12) / 1024^3 = 7450.6GB
. Do you have this much RAM on your machine?
Compare this with a = zeros(1, 1e6)
which creates a column-vector of size 1 * 1e6 = 1e6
, for a total allocated size of (8 * 1e6) / 1024^3 = 7.63MB
.
Logicals
Logical values, on the other hand are boolean values, which can be set to either 0
or 1
representing False
or True
. With this in mind, you can allocate matrices of logicals using either false()
or true()
. Here the same single-argument rule applies, hence a = false(1e6)
creates a square matrix of size 1e6 * 1e6 = 1e12
. Matlab today, as many other programming languages, stores bit values, such as booleans, into single Bytes. Even though there is a clear cost in terms of memory usage, such a mechanism provides significant performance improvements. This is because it is accessing single bits is a slow operation.
The total allocated size of our a = false(1e6)
matrix would therefore be 1e12 Bytes
which is circa 1e12 / 1024^3 = 931.32GB
.
a=ones(100000);
is equivalent toa=ones(100000,100000);
– Divakar