0

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!

2 Answers 2

2

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   
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that would work, thanks :) Was still hoping for something cleaner without a loop, hehe.
1

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   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.