【问题标题】:Loading a data efficiently in matlab在matlab中有效地加载数据
【发布时间】:2013-12-18 01:53:26
【问题描述】:

我在一个文本文件中有以下形式的数据

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

总共有 81 个 Gameid,我有大约 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

【问题讨论】:

  • 我不确定你希望你的稀疏矩阵是什么样子。您是否希望它同时包含值 玩家姓名字符串?或者,您想为每个玩家创建一个稀疏矩阵吗?

标签: matlab


【解决方案1】:
  • 避免内部循环,再次使用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 列标题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 2016-05-04
    • 2020-08-11
    • 2018-05-23
    • 2014-01-26
    • 1970-01-01
    • 2013-01-22
    相关资源
    最近更新 更多