Reputation: 694
I would like to make out of a big string a cell array, e.g. I have :
str1 = ['aa1','bb1','cc1'];
str2 = ['aa2','bb2','cc2'];
The question is how to make out of each comma separated string entry, seperate cell array entry. Im looking for something similar like
dataCell = {eval(str1),';', ...
eval(str2)};
At the end I want to have the following :
dataCell = {'aa1','bb2','cc2'; 'aa2','bb2','cc2'}
I could have gone over loop and do something like
dataCell {end+1} = 'string';
but I wanted to do all at once, if possible.
Thanks in advance.
PS The question is which of all solutions it the best in terms of performance ?
Upvotes: 1
Views: 1260
Reputation: 3116
To begin with, I would like to point out that str=['aa1','bb1','cc1'];
is a char variable which is composed of the three strings concatenated (as opposed to str=['aa1';'bb1';'cc1'];
which is a 3 by 1 char array).
Assuming that you meant to have a char array, then you can use the function mat2cell
to build cell array from your char array:
str1=['aa1';'bb1';'cc1'];
str2=['aa2';'bb2';'cc2'];
dataCell1=mat2cell(str1,ones(1,size(str1,1)),size(str1,2));
dataCell2=mat2cell(str2,ones(1,size(str2,1)),size(str2,2));
dataCell=[dataCell1 dataCell2]';
Which gives you the following cell array:
'aa1' 'bb1' 'cc1'
'aa2' 'bb2' 'cc2'
UPDATE: as you seem concerned about performance, I ran a little test to compare the build time of a cell array from a n by n character array. This is not a precise benchmark but it gives interesting results.
n=5;
Elapsed time is 0.008 seconds for mat2cell.
Elapsed time is 0.002 seconds for cellstr
Elapsed time is 0.0003 seconds for the loop.
n=500;
Elapsed time is 0.015 seconds for mat2cell.
Elapsed time is 0.005 seconds for cellstr.
Elapsed time is 0.0015 seconds for the loop.
n=5000;
Elapsed time is 0.64 seconds for mat2cell.
Elapsed time is 0.20 seconds for cellstr.
Elapsed time is 0.16 seconds for the loop.
If you want to test it out (or correct my possible mistakes), here is how I did:
clear all;
n=500;
str=[repmat('a',1,n)];
strarray=repmat(str,n,1);
tic;
strcell=mat2cell(strarray,ones(1,size(strarray,1)),size(strarray,2));
toc;
clear all;
n=500;
str=[repmat('a',1,n)];
strarray=repmat(str,n,1);
tic;
strcell=cellstr(strarray);
toc;
clear all;
n=500;
str=[repmat('a',1,n)];
strarray=repmat(str,n,1);
tic;
strcell=cell(size(strarray,1),1);
for i=1:size(strarray,1)
strcell{i}=strarray(i,:);
end
toc;
Upvotes: 1
Reputation: 3608
I like these kind of questions because it can show you all kinds of different ways to do the same thing:
str1=['aa1';'bb1';'cc1'];
str2=['aa2';'bb2';'cc2'];
data = [cellstr(str1) cellstr(str2)]'
data =
'aa1' 'bb1' 'cc1'
'aa2' 'bb2' 'cc2'
Again this is assuming str1 and str2 are;
separated.
Upvotes: 4
Reputation: 9645
I guess you mean
str1 = ['aa1';'bb1';'cc1'];
str2 = ['aa2';'bb2';'cc2'];
otherwise you just get a single vector for each variable. in that case, you should use:
mat2cell([str1;str2],ones(1,6),3)
Upvotes: 0