prolem in sparse
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Sven
am 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.
Akzeptierte Antwort
Sven
am 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 Kommentare
Sven
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!