prolem in sparse
조회 수: 4 (최근 30일)
이전 댓글 표시
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
Sven
2011년 11월 18일
"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.
채택된 답변
Sven
2011년 11월 18일
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
Sven
2011년 11월 25일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!