将矩阵转换为单元格字符串,其元素由分隔符分隔

时间:2014-11-24 19:35:22

标签: string matlab matrix cells

如何转换矩阵

A=[1,2,3;4,5,6]

到字符串

的单元格
A_str = {'1_2_3';'4_5_6'};

3 个答案:

答案 0 :(得分:2)

一种方法可能就是这个 -

%// Input
A=[1,2,3;4,5,6] 

%// Make a cell array with each element a string off each element of A
cells = cellfun(@(x) num2str(x),num2cell(A),'Uni',0)

%// Join the cells with strjoin using `_` as the delimiter 
A_str = arrayfun(@(n) strjoin(cells(n,:),'_'),1:size(cells,1),'Uni',0).'

输出 -

A_str = 
    '1_2_3'
    '4_5_6'

答案 1 :(得分:1)

发现这个解决方案似乎更快

A=[1,2,3;4,5,6] 

A_str = cell(size(A,1),1);
for index_row = 1 : size(A,1)
    clear allOneString_temp
    allOneString_temp = sprintf('%.0f_' , A(index_row,:));
    A_str{index_row,:} = allOneString_temp(1:end-1);
end

答案 2 :(得分:0)

另一种方法,没有循环:

A_str = num2str(A,'%i_');
A_str = mat2cell(A_str(:,1:end-1), ones(1,size(A_str,1)));