prolem in sparse

1 view (last 30 days)
huda nawaf
huda nawaf on 18 Nov 2011
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
  2 Comments
Sven
Sven on 18 Nov 2011
"when I create file to store this matrix ,was not created"
Did you create it or not? If you *tried* to create it, what did you try? And what went wrong? Please show exactly what you tried.
huda nawaf
huda nawaf on 18 Nov 2011
I created sparse matrix but don't now how store it in txtfile

Sign in to comment.

Accepted Answer

Sven
Sven on 18 Nov 2011
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
  18 Comments
huda nawaf
huda nawaf on 24 Nov 2011
i want to say , before ask i look for
please,regarding cell
if i want to do the following with cell, how do it?i don't know how cell works
for i=1:5
for j=1:not defined
a(i,j)=any value
end
end
regarding txt file
no, i don't need open it in another program
i use it in matlab only.
what other options,and why?
do u mean creat .m or .dat in stead of .txt , if so why? what i will get in this case
Sven
Sven on 25 Nov 2011
Huda, I've updated the answer again to include how to use a cell. Please read the doc section on "Access Data in a Cell Array".
You should use load() and save() because it is the *simplest* way to save and load your data. You don't need to worry about converting to text or converting from text... all this is handled by MATLAB.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!