【问题标题】:Matlab: Use Splitapply to write multiple filesMatlab:使用Splitapply编写多个文件
【发布时间】:2019-11-19 18:26:54
【问题描述】:

我已经按变量对表进行了分组,我正在尝试根据分组变量编写多个文件。但它不起作用。

我使用了findgroupssplitapply,但splitapply 是我遇到问题的地方。

这是我正在使用的命令的一个版本:

load patients;
G=findgroups(Gender);
func=@(x,y) csvwrite(x,y);
splitapply(func,Gender,Weight,G);

我收到以下错误消息:

使用 splitapply 时出错(第 132 行)
将函数 '@(x,y)csvwrite(x,y)' 应用于第一组数据会产生以下错误:

FILENAME 必须是字符向量或字符串标量。

当我弄清楚如何使用它时,我将在大型数据存储 tall 数组上使用它。请帮忙!

【问题讨论】:

  • 什么不起作用?您收到错误消息吗?如果是这样,你会得到什么错误?

标签: matlab split-apply-combine


【解决方案1】:

问题是csvwrite的第一个参数必须是文件名

在您的代码示例中,csvwrite 的第一个参数是元胞数组,而不是字符串。

您可以使用以下技巧来查看它:

func=@(x,y) display(x);

splitapply(func,Gender,Weight,G) 的输出为:

x =

  53×1 cell array

    {'Female'}
    {'Female'}
    {'Female'}
   ...

x =

  47×1 cell array

    {'Male'}
    {'Male'}
    {'Male'}

解决方案:
使用x{1} 而不是x

func=@(x,y) csvwrite(x{1}, y);

建议在文件名中添加.txt之类的文件扩展名:

func=@(x,y) csvwrite([x{1}, '.txt'], y);

备注:
splitapplycsvwrite 的组合可能会错过 splitapply 函数的初衷。
根据文档,splitapply 看起来更适合统计计算(并且不打算用于 I/O 操作 [写入文件])。
我不确定上述代码模式是否是“在大型数据存储高阵列上使用它”的正确方法。


完整的代码示例:

load patients;
G=findgroups(Gender);

%The first parameter of csvwrite must be a file name.
%x{1} = 'Male' for all the Male group, and 'Female' for all the Female group.
%[x{1}, '.txt'] adds a '.txt' extension to the file name.
%
%y will be array of Weight like
%[71
% 69
% 68]
func=@(x,y) csvwrite([x{1}, '.txt'], y);

splitapply(func,Gender,Weight,G)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2017-05-30
    相关资源
    最近更新 更多