使用strjoin时出错

时间:2015-02-27 12:52:28

标签: matlab

所以我正在使用这个示例代码,

 --- Define M
M = [sprintf('%s\t%s\n', 'a', 'b') ...
    sprintf('%s\t%s\n', '011', '10') ...
    sprintf('%s\t%s\n', '001', '10') ...
    sprintf('%s\t%s\n', '112', '4') ...
    sprintf('%s\t%s\n', '015', '2') ...
    sprintf('%s\t%s\n', '086', '1') ...
    sprintf('%s\t%s\n', '117', '1') ...
    sprintf('%s\t%s\n', '121', '2')]

% --- Convert into cells
tmp = textscan(M, '%s\t%s\n');
C1 = tmp{1};            % First column
C2 = tmp{2};            % Second column

% --- Group

% Get unique values of the second column
UV = unique(C2);

% Prepare result columns
R1 = {};
R2 = {};

% Group
for i = 1:numel(UV)

    b = ismember(C2, UV{i});
    R1{i,1} = strjoin(C1(b), ',');
    R2{i,1} = strjoin(C2(b), ',');

end

% --- Convert the result to a string
Res = '';
for i = 1:numel(R1)
    Res = [Res sprintf('%s\t%s\n', R1{i}, R2{i})];
end

但是它给出了一个错误:使用strjoin时出错(第52行) 第一个输入必须是1xN字符串数组。

我正在使用R2014a版本的matlab,我不知道如何解决这个错误,我真的需要那些代码请帮忙谢谢。

1 个答案:

答案 0 :(得分:1)

运行代码时我也遇到了错误(R2013a)。由于C1C1是大小为8x1的单元格数组,因此实际上需要对它们进行转置以避免错误(从而获得strjoin请求的大小为1x8的单元格数组)。这有点愚蠢,它本身不会进行转置。

在提供错误的循环之前添加这两行并且运行正常:

C1 = C1.';
C2 = C2.';

完整代码:

M = [sprintf('%s\t%s\n', 'a', 'b') ...
    sprintf('%s\t%s\n', '011', '10') ...
    sprintf('%s\t%s\n', '001', '10') ...
    sprintf('%s\t%s\n', '112', '4') ...
    sprintf('%s\t%s\n', '015', '2') ...
    sprintf('%s\t%s\n', '086', '1') ...
    sprintf('%s\t%s\n', '117', '1') ...
    sprintf('%s\t%s\n', '121', '2')]

% --- Convert into cells
tmp = textscan(M, '%s\t%s\n');
C1 = tmp{1};            % First column
C2 = tmp{2};            % Second column

% --- Group

% Get unique values of the second column
UV = unique(C2);

% Prepare result columns
R1 = {};
R2 = {};

C1 = C1.';
C2 = C2.';

% Group
for i = 1:numel(UV)

    b = ismember(C2, UV{i});
    R1{i,1} = strjoin(C1(b), ',');
    R2{i,1} = strjoin(C2(b), ',');

end

% --- Convert the result to a string
Res = '';
for i = 1:numel(R1)
    Res = [Res sprintf('%s\t%s\n', R1{i}, R2{i})];
end

这样做我得到了

Res =

086,117 1,1
011,001 10,10
015,121 2,2
112 4
a   b