Stefan
Stefan

Reputation: 444

Matlab: 2D cell array to char array

I was wondering if there is a nice way in which I can convert my 2D cell array into a 2D char matrix.

The cell array looks like this:

'test'    'me'    '0'     '22' 
'tester'  'me'    '14'    '241'
'test'    'you'   '25'    '1'  

And now I would like to put spaces between the columns and make the whole thing a char array. Meaning I want either this:

'test me 0 22    '
'tester me 14 241'
'test you 25 1   '

or this

'test   me  0   22'
'tester me  14 241'
'test   you 25   1'

Could you help me out? I tried char() but it doesn't care that the cell array is 2D and just creates one row for each element in the cell array.

EDIT: In case someone wants to get back a cell array of the concatenated rows look at this Combine Columns of Cell Array Matlab

Many thanks!

Upvotes: 0

Views: 892

Answers (2)

RTL
RTL

Reputation: 3587

I can only see how to do it while matching the format specified with a simple loop, if format is not important using char and reshape as nkjt did is the best I can see...

cellArray={ snip };

outp=[]

for ii=1:size(cellArray,2)
outp=[outp str2mat(cellArray(:,ii)) blanks(size(cellArray,1))'];
end

works column-wise using str2mat to concatenate each column into a (padded) char array, adding a trailing space, then adding to the output.

results:

outp =

test   me  0  22  
tester me  14 241 
test   you 25 1   

Upvotes: 1

nkjt
nkjt

Reputation: 7817

Well, char gets you part of the way there, and some mucking about with reshape etc. does the rest:

out = char(C');
out(:,end+1)=' ';
out = reshape(out',[28,3]);
out = out';

(has perhaps more spaces in than you wanted)

However, a better way might be to pad the internal strings in the cell array so the total length is the same in each row, then add

f = @(x) [x,' '];
% need at least one space after each entry
C = cellfun(f,C,'UniformOutput',0); 
% now work out how much extra length needed
l = cellfun(@length,C);
l = sum(l,2);
l = max(l)-l;
% pad
for n = 1:length(l)
    C{n,end} = [C{n,end},blanks(l(n))];
end

Now all we need is:

cell2mat(C)

ans =

test me 0 22      
tester me 14 241  
test you 25 1   

Upvotes: 2

Related Questions