2016-02-22 18 views
1

鉴于以下格式的表在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

我无法想到没有循环的解决方案。

  • 使用逻辑索引
  • 运行这样仅环中号倍(如果中号是唯一itemid元素的数量),而不是ñ倍(如果:但是你可以优化你的循环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