Import data of form <<(index, index) value>> into sparse matrix
I've got a plain text data file (.dat) containing sparse matrix information that I'd like to import into MATLAB. It looks a bit like:
(1,2) 1
(2,3) 2
And so forth, where we've got the index for matrix position in the left hand column, and the value to go there in 开发者_C百科the right. Searching around hasn't turned up a nice and easy way to do this, but I don't have an overwhelming amount of experience with MATLAB, so I don't know if I'm missing something obvious.
You can use function spconvert
Examples:
Suppose the ASCII file uphill.dat contains
1 1 1.000000000000000
1 2 0.500000000000000
2 2 0.333333333333333
1 3 0.333333333333333
2 3 0.250000000000000
3 3 0.200000000000000
1 4 0.250000000000000
2 4 0.200000000000000
3 4 0.166666666666667
4 4 0.142857142857143
4 4 0.000000000000000
Then the statements
load uphill.dat
H = spconvert(uphill)
H =
(1,1) 1.0000
(1,2) 0.5000
(2,2) 0.3333
(1,3) 0.3333
(2,3) 0.2500
(3,3) 0.2000
(1,4) 0.2500
(2,4) 0.2000
(3,4) 0.1667
(4,4) 0.1429
You can try using scanf
. Here's some code to start with:
fid = fopen('sparse.dat', 'rt');
[m n] = fscanf(fid, '(%d,%d) %d\n');
fclose(fid);
m = reshape(m, 3, length(m)/3)';
% m should now be:
% [1 2 1; 2, 3, 2]
精彩评论