How to save a numeric value in a specified location of a CSV file inside for loops?

1 view (last 30 days)
I want to do this because otherwise I run out of memory to save the values in a matrix, as the dimensions of the matrix increases.
For example,
for a=1:10000
for b=1:10000
M(a,b)=rand;
end
end
Here, the system runs out of memory as it can't store a 10000x10000 matrix.
So, I want to keep writing the (a,b)'th value inside the for loops into the (a,b)'th cell of a csv file (or an xls file, whatever). How do I do that?
I want something like this:
for a=1:10000
for b=1:10000
xlswrite1('file.xls',rand,a,b); % better if I can get a solution with csvwrite, as I prefer CSVs to work with
end
end
But this obviously doesn't work. The error it gives is:
Error using evalin
Undefined function or variable 'Excel'.
Error in xlswrite1 (line 2)
Excel=evalin('caller','Excel');
Then when I add the following lines according to this article,
Excel = actxserver ('Excel.Application');
File='datafile.xls';
if ~exist(File,'file')
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);
it gives this error:
Error using xlswrite1 (line 82)
Range argument must a string of Excel A1 notation.
Can anyone please suggest a simple solution? I can't find any from my online search so far.

Answers (1)

KSSV
KSSV on 8 Jun 2017
You can do this using dlmwrite. But I suggest you to write row by row instead of element by element.
N = 100 ;
M = zeros(N,N) ;
filename = 'test.csv';
for a=1:N
for b=1:N
M(a,b)=rand;
end
dlmwrite(filename,M(a,:),'-append')
end

Community Treasure Hunt

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

Start Hunting!