out of memory error when write matrix
Show older comments
"I need to define a matrix A=zeros(N,N) where N is a very large number.
Is there a way to write the matrix without encountering the out of memory error?"
Answers (2)
You could make it sparse,
A=sparse(N,N);
but be mindfult that if you then want to populate the A(i,j) with non-zero numbers, it will be very slow to do so one at a time. The more efficient way to populate a sparse matrix is,
Steven Lord
on 10 Feb 2024
Moved: Steven Lord
on 10 Feb 2024
How large a "very large number" are we talking about?
Such a matrix would require a block of contiguous memory 8*N^2 bytes in size (assuming full real double.)
For some values of N, this is easily achievable.
N = 10;
A = zeros(N);
For some values of N, it's theoretically possible depending on your machine and what else you have running on it.
For some values of N, it's technically theoretically possible but there's no machine with enough memory to create it.
For some values of N, it's not even theoretically possible.
[~, maxelements] = computer;
N = ceil(sqrt(maxelements))
A = zeros(N);
If you do need to work with data that's that large, using sparse matrices (as Matt J suggested) is one option. The tools listed in this section of the documentation provides other options.
3 Comments
FRANCESCO MICELI
on 10 Feb 2024
Matt J
on 10 Feb 2024
That's not very large for a sparse matrix, unless you are telling us that most of those 60000x60000 are non-zero.
So how large a contiguous block of memory would a real full double matrix that size require?
N = 60000;
bytes = 8*N^2;
gb = bytes/(1024^3)
That's pretty large. Let's check my calculations by asking MATLAB Answers to create such a matrix.
A = zeros(N);
Perhaps if you tell us your application we may be able to offer some suggestions for alternate ways to solve the problem without requiring creating such a large matrix.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!