MATLAB: Prolem in sparse

sparse

hi,
to avoid out of memory I used sparce matrix
x=sparce(10,10);
x(1:10,1:10)=5;
when I need to store this matrix in file
how do that
where the x be as:
(1,10) 5
(2,10) 5
(3,10) 5
(4,10) 5
(5,10) 5
when I create file to store this matrix ,was not created
thanks

Best Answer

Huda, try this (edited to update with comments):
% Make Data
x=sparse(10,10);
x(1:10,1:10)=5;
% Get the rows, cols, values of any non-zero elements
[rows,cols,vals] = find(x);
% Save to a text file
fid = fopen('myFile.txt','w')
fprintf(fid, '(%d,%d)\t%f\n',[rows,cols,vals]')
fclose(fid)
And then to later open and read it:
fid = fopen('myFile.txt','r');
[R,C,V] = textscan(fid, '(%d,%d)\t%f');
fclose(fid)
Keep in mind a few things:
1. If you only want to save these files then read them back into MATLAB, it's much simpler to use save() and load(). For example:
myData = {[2 5 32], [1 2 3 4 5 6 7], [12 23 34]};
save('myFile.mat', 'myData')
clear myData % This just deletes the variable "myData"
load('myFile.mat') % This just loads it again!
2. If you're setting the value of every element in a sparse matrix to a non-zero value, then you shouldn't be using a sparse matrix in the first place... sparse matrices are the most efficient when the majority of elements in your matrix are zeros. Instead, you should use a cell array of vectors like this:
myData = {[2 5 32], [1 2 3 4 5 6 7], [12 23 34]};
for i = 1:length(myData)
for j = 1:length(myData{i})
fprintf('Cell #%d, Element #%d, equals %f\n', i, j, myData{i}(j))
end
end