2013-12-17 29 views
3

我有以下形式的数据在一个文本文件有效地加载数据在MATLAB

Userid Gameid Count 
Jason 1  2 
Jason 2  10 
Jason 4  20 
Mark 1  2 
Mark 2  10 
................ 
................. 

总共有81个Gameids的,我有200万左右的不同用户。

我要的是读取该文本文件并创建表单的稀疏矩阵

 Column 1 2 3 4 5 6 . 
Row1 Jason 2 10 20 
Row2 Mark 2 10 

现在我可以加载在MATLAB这个文本文件并读取用户一个接一个,阅读他们的数量和初始化稀疏数组。我已经试过了,初始化一个用户的行需要1秒。所以对于总共200万用户来说,这需要我很多时间。

什么是最有效的方法来做到这一点?

这里是我的代码

data = sparse(10000000, num_games); 
loc = 1; 

for f=1:length(files) 
    file = files(f).name; 

    fid = fopen(file,'r'); 

    s = textscan(fid,'%s%d%d'); 

    count = (s(:,2)); 
    count = count{1}; 
    position = (s(:,3)); 
    position = position{1}; 

    A=s{:,1}; 
    A=cellstr(A); 

    users = unique(A); 

    for aa = 1:length(Users) 
     a = strfind(A, char(Users(aa))); 
     ix=cellfun('isempty',a); 
     index = find(ix==0); 
     data(loc,position(index,:)) = count(index,:); 
     loc = loc + 1; 
    end 
end 
+0

我不知道你希望你的稀疏矩阵看起来像。你想要它包含值*和*球员姓名字符串?或者,您是否想为每个玩家创建一个稀疏矩阵? –

回答

2
  • 使用unique更加为GameID避免内循环。
  • 存储用户名称,因为在您的原始代码中,无法确定哪个名称 - 与每行相关。游戏ID也是一样。
  • 确保在打开文件后关闭文件。
  • sparse矩阵不支持'int32'您需要将数据存储为double

% Place holders for Count 
Rows = []; 
Cols = []; 

for f = 1:length(files) 
    % Read the data into 's' 
    fid = fopen(files(f).name,'r'); 
    s = textscan(fid,'%s%f%f'); 
    fclose(fid); 

    % Spread the data 
    [U, G, Count{f}] = s{:}; 

    [Users{f},~, r] = unique(U); % Unique user names 
    [GameIDs{f},~,c] = unique(G); % Unique GameIDs 

    Rows = [Rows; r + max([Rows; 0])]; 
    Cols = [Cols; c + max([Cols; 0])]; 
end 

% Convert to linear vectors 
Count = cell2mat(Count'); 
Users = reshape([Users{:}], [], 1); 
GameIDs = cell2mat(GameIDs'); 

% Create the sparse matrix 
Data = sparse(Rows, Cols, Count, length(Users), length(GameIDs), length(Count)); 

Users将包含成为行标题(用户名)和GameIDs列标题