Вы можете использовать textscan
с помощью спецификатора формата %d:%f
, чтобы получить эту информацию. Вот полный пример того, как это можно сделать.
fid = fopen(filename, 'r');
%// Get the label of the first line
label = fscanf(fid, '%d', 1);
%// Initialize matrix to hold the result
%// If you know what the maximum label will be you can make this the right size
m = zeros(0,9);
%// Row counter
row = 1;
%// Loop until we hit the end of the file
while ~feof(fid)
%// Look for a number followed by a colon and another number
data = textscan(fid, '%d:%f');
values = data{2};
columns = data{1}(1:numel(values));
%// Fill the matrix at the columns that we loaded using the label as the row
m(row, columns) = values;
%// The next label was automatically picked up because it matched %d
row = row + 1;
end
fclose(fid);
Я испытал это на следующем входе:
1 1:0.73 2:0.04 3:0.95 4:1 6:0.36 7:0.30 8:0.61
2 2:0.99 2:0.45 5:0.99 4:2 7:0.5 9:10
3 1:-2 9:12
И был в состоянии произвести следующую матрицу
m =
0.73 0.04 0.95 1 0 0.36 0.3 0.61 0
0 0.45 0 2 0.99 0 0.5 0 10
-2 0 0 0 0 0 0 0 12
Update
Если у вас есть очень большой матрица, и она малонаселена, вы можете вместо этого для создания разреженной матрицы из данных используйте следующее.
fid = fopen(filename, 'r');
%// Get the label of the first line
label = fscanf(fid, '%d', 1);
%// Initialize rows/cols/values array
[rows, cols, vals] = deal([]);
%// Row counter
row = 1;
%// Loop until we hit the end of the file
while ~feof(fid)
%// Look for a number followed by a colon and another number
data = textscan(fid, '%d:%f');
columns = data{1}(1:numel(data{2}));
%// Append data to rows/cols/vals arrays
vals = cat(1, vals(:), data{2});
cols = cat(1, cols(:), double(columns(:)));
rows = cat(1, rows(:), row + zeros(size(columns(:))));
%// The next label was automatically picked up because it matched %d
row = row + 1;
end
fclose(fid);
%// Create the sparse matrix
m = sparse(rows, cols, vals);
Я пробовал ваш код, но он выдает ошибку из памяти с файлом 2000 строк. – Dharmendra
Каковы максимальные значения для 'label' и максимального' index'? – Suever
@Dharmendra Я подозреваю, что ваша матрица является разреженной матрицей. Попробуйте код в разделе «Обновление» моего ответа – Suever