Darren J. Fitzpatrick
Darren J. Fitzpatrick

Reputation: 7409

MATLAB - concatenating items within a cell array

I have a cell array:

X =

{1x2} {1x2}


X{1} = '' A

X{1 2} = 10 113

I wish to concatenate the sub cells in such a way that

 Y = 10 113A

Thanks, S :-)

Upvotes: 0

Views: 3558

Answers (4)

Superbest
Superbest

Reputation: 26592

The Matlab File Exchange has a function written to do precisely this. uniqueRowsCA

Upvotes: 0

gnovice
gnovice

Reputation: 125854

Assuming you have this cell array for X:

X = {{'' 'A'} {10 113}};

You can create your array Y using INT2STR and STRCAT:

Y = strcat(int2str([X{2}{:}].'),X{1}.').';

Upvotes: 1

SCFrench
SCFrench

Reputation: 8374

y = cellfun(@(a, b) sprintf('%d%s', b, a), x{1}, x{2}, 'UniformOutput', false);

Upvotes: 1

Darren J. Fitzpatrick
Darren J. Fitzpatrick

Reputation: 7409

For those interested, I think I found a solution.

I redefined my cell array as:

X1 =

{1x2}

X1 = '' 'A'

X2 = 

[1x2 double]

X2 = 10 113

I then applied this for loop:

NUM = [];

for i = 1:size(X2')              #take the transpose of X2
    p = num2str(X2(i));          #convert doubles to strings
    str = STRCAT(p, X1(i));      #concatenate
    NUM = [NUM str];             #add to another array
end


NUM = '10' '113A'

I am sure there is a more efficient way but MATLAB and I will probably never be on good terms. Sometimes quick and dirty is sufficient!

Cheers, S :-)

Upvotes: -1

Related Questions