【问题标题】:getting a cell array of string into a matrix or table Matlab将字符串的单元格数组放入矩阵或表 Matlab
【发布时间】:2014-04-14 07:40:13
【问题描述】:

我正在从对某些数据执行的计算中收集信息并存储到数组中。我还有一些关于这些数据的信息,这些数据来自一个不时包含字符串的文本文件。

文本文件中的字符串保存到{} 字符串元胞数组中,例如:

strings={'s1' 's2' 's3'};
a=[1 2 3]

字符串和数组包含的内容是根据文本文件中存在的数据以及我在 matlab 中通过执行类似操作的一些数据中的一些条件生成的:

srings{e}=blablahFromSomewhere{e}
a(e)=otherNumericalBlahBlahFromSomwehre(e+6)

最终我想把它合并成一张桌子。我通常会这样做:

T=[a(:) strings(:)]

但我面临以下错误:

Error using horzcat
Dimensions of matrices being concatenated are not consistent.

有人可以帮忙吗?我真的不想将字符串转换为整数,因为在运行分析时,字符串的内容在输出中更方便。

谢谢:)

【问题讨论】:

    标签: string matlab concatenation cell-array


    【解决方案1】:

    代码

    strings={'s1' 's2' 's3'};
    a=[1 2 3];
    outputfile = 'output.txt';
    
    %%// Code to horziontally concatenate to result in a Nx2 cell array
    out = [num2cell(num2str(a,'%d')') strings']
    
    %%// Write to outputfile - Method 1
    out = out';
    fid = fopen(outputfile,'w');
    fprintf(fid, '%s\t%s\n', out{:});
    fclose(fid);
    
    %%// Write to outputfile - Method 2
    %%// Create a text file and clear it out of any content. This is needed, as otherwise
    %%// XLSREAD was initializing CSV files with weird characters
    %% dlmwrite(outputfile,'');
    
    %%// Write to CSV file using XLSREAD
    %xlswrite(outputfile,out)
    
    %%// Verify
    type(outputfile)
    

    输出

    out = 
    
        '1'    's1'
        '2'    's2'
        '3'    's3'
    
    
    1   s1
    2   s2
    3   s3
    

    【讨论】:

    • 好吧,这已经很接近了,但是当我使用下面的dlmwrite(fileName,T,'-append','delimiter','\t'); 时,字符串会分成与标签一样多的“列”。
    • 已根据您的新要求进行编辑!
    • 感谢您的回复。可悲的是,它给了我用逗号分隔的每个字符。我还收到一个错误,它无法启动 Excel。这是一项令人头疼的任务
    • 看来xlswrite 是只有PC 的东西。下载了第三方开发的 mac 的“修复”,但我只会保存在 xls 中,这最终不是很方便,因为这个表必须去 R. 该死的 MATLAB!
    • 太棒了!高超!非常感谢您的帮助和耐心!
    【解决方案2】:

    有点不清楚你想要什么,但似乎是:

    T = table(a(:), strings(:));
    

    假设我正在正确阅读table 的文档。

    或者,对于元胞数组:

    C = [num2cell(a(:)) strings(:)];
    

    【讨论】:

    • 认为这将是完美的,但因为我使用 dlmwrite 写入文本文件,我得到以下信息:Error using dlmwrite (line 118) The input cell array cannot be converted to a matrix.
    • @Bastien 我从未使用过它,但根据文档dlmwrite 只处理数字数据,而不是字符串。如果您有足够新的 Matlab 或统计工具箱,使用表格和writetable 看起来可能会起作用。 More ideas here.
    • 遗憾的是我没有写表...我只是一个有那个sadface的版本
    【解决方案3】:

    如果要获取char数组:

        aux = num2str(a(:));
        aux = mat2cell(aux,ones(1,size(aux,1)),size(aux,2));
        T = cell2mat([aux strings(:)]);
    

    结果是一个二维字符数组(如果需要,可以引入前导空格):

        T =
    
        1s1
        2s2
        3s3
    

    【讨论】:

    • OP 已经提到 - “T=[a(:) strings(:)]”,所以我认为他需要一个单元格输出。
    • 嘿@Luis 谢谢。这不是我想要的。最终表应包含两列,一列用于a,另一列用于strings
    • @Bastien 所以...你想要一个二维单元阵列作为结果吗?
    • 我猜二维单元阵列可以做到。
    • 虽然 dlmwrite 可能不喜欢它(请参阅我的评论以在下面回答)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    相关资源
    最近更新 更多