将具有数字数组的字符串的单元格数组转换为矩阵

时间:2016-10-06 10:56:19

标签: arrays matlab matrix cell

我的单元格数组有不同长度的字符串:

rr ={'1 2 5';
     '5 6 1';
     '12 56 2';
     '12 1';
     '343 2 -5 1 5';
     '1  5  3  2 0'}

我想根据字符串长度制作不同的数字矩阵而不是字符串:

a1 = [1 2 5; 5 6 1; 12 56 2]
a2 = [12 1]
a3 = [343 2 -5 1 5; 1  5  3  2 0]

我有一大套,我的实际数据会有很多矩阵,例如a1a2a3

1 个答案:

答案 0 :(得分:2)

这是一种方式:

rr ={'1 2 5';
     '5 6 1';
     '12 56 2';
     '12 1';
     '343 2 -5 1 5';
     '1  5  3  2 0'}

%// convert 
x = cellfun(@(x) sscanf(x,'%f'), rr,'uni',0)
%// count
n = cellfun(@numel,x)
%// distribute
s = accumarray(n,1:numel(n),[],@(ii) {x(ii)} )
%// remove empty elements
s = s(~cellfun('isempty',s)) 
%// assign
m = cellfun(@(y) [y{:}].' ,s, 'uni',0)

%// last step I'd try to avoid
[a,b,c] = m{:};
a =

    12     1


b =

    12    56     2
     5     6     1
     1     2     5


c =

     1     5     3     2     0
   343     2    -5     1     5

我建议您避免最后一步并继续使用单元格阵列m,因为您事先并不知道有多少 a1 a2 ......等等你需要。结构也是一个不错的选择。

相关问题