将关键字数据放入csv文件MATLAB中

时间:2016-02-22 18:24:18

标签: matlab csv

在MATLAB中给出以下格式的表格:

     userid | itemid | keywords
A = [ 3        10       'book'
      3        10       'briefcase'
      3        10       'boat'
      12       20       'windows'
      12       20       'picture'
      12       35       'love'
      4        10        'day'
      12       10        'working day'
      ...     ...        ... ];

其中A是一个大小的表(58000 * 3),我想用csv文件写下数据,格式如下:

csv.file

    itemid  keywords
      10    book, briefcase, boat, day, working day, ...
      20    windows, picture, ...
      35    love, ...

我们itemids的列表存储在Iids = [10,20,35,...]

我想避免使用循环,因为你可以想象矩阵是大尺寸的。任何想法都表示赞赏。

1 个答案:

答案 0 :(得分:1)

我无法想到没有循环的解决方案。但您可以通过以下方式优化循环:

  • 使用逻辑索引
  • 仅运行此类循环 M 次(如果 M 是唯一itemid元素的数量)而不是 N 次(如果 N 是表格中元素的数量。)

我想出的解决方案就是这个 首先,创建你的表

A=table([3;3;3;12;12;12;4;12], [10;10;10;20;20;35;10;10],{'book','briefcase','boat','windows','picture','love','day','working day'}','VariableNames',{'userid','itemid','keywords'});

看起来像

enter image description here

选择列itemid(您的Iids)的唯一值:

Iids=unique(A.itemid);

看起来像

enter image description here

创建一个新的空表,其中包含结果:

NewTable=table();

现在我提出了最小的循环:

for id=Iids'
    % select rows with given itemid value
    RowsWithGivenId=A(A.itemid==id,:);

    % create new row in NewTable with the id and the (joined together) keywords from the selected rows
    NewTable=[NewTable; table(id,{strjoin(RowsWithGivenId.keywords,', ')})];
end

另外,在NewTable

中添加新列名称
NewTable.Properties.VariableNames = {'itemid','keywords'};

现在NewTable看起来像:

enter image description here

请注意:由于新表中的关键字以逗号分隔,因此csv文件不是我推荐的格式。将writetable()用作writetable(NewTable,'myfile.csv'); 你得到的是

enter image description here

相反,通过替换;而不是分隔逗号(在strjoin()中),您将获得更好的格式:

enter image description here

相关问题