How to extract every elements with different dimension at multiple cells in efficient manner?

1 view (last 30 days)
Dear all,
Say I have three cells, where the element
dd = [49;50;51;52;53;54] [55;56;57] [85;86;87;88;89;90]
The objective is to extract all the element in each cell and make it into single row, such that
[40 50 51 52 53 54 55 56 57 85 86 87 88 89 90]
I used the following lines.
C =1
for i =1:size(dd,2)
Xcx = cell2mat (dd (1,i));
ee =[]
ee (1,1: length (Xcx)) =Xcx;
for k =1: length (ee )
new (C,1) = ee (k)
C =C+1
end
end
Even though the code do the trick, I am looking if there is more advance and compact ways of doing it?
Thanks in advance

Accepted Answer

balandong
balandong on 3 Aug 2017
Edited: balandong on 3 Aug 2017
Dear Akira, Thanks for your response, I give an idea of using the VERTCAT. Using VERTCAT instead of HORZCAT skip the need of CELLFUN and TRANSPOSE.
dd = {[49;50;51;52;53;54], [55;56;57], [85;86;87;88;89;90]};
output1 =vertcat (dd{:});
Thanks for your answer, however I had to accept this solution as a better and more compact ways.

More Answers (2)

Sanjay Nair
Sanjay Nair on 2 Aug 2017
Hello,
If I'm understanding your problem correctly you have a cell array that can be defined in the following manner
dd = {[49;50;51;52;53;54], [55;56;57], [85;86;87;88;89;90]};
Since you have a cell array of column vectors with only three elements, perhaps the easiest way to extract them into a single row vector would be to transpose and concatenate the contents in a single command as follows:
row = [dd{1}', dd{2}', dd{3}'];
You can get more information about accessing data in cell-arrays in: https://www.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html
  1 Comment
balandong
balandong on 3 Aug 2017
HI Sanjay, Thanks for your response and idea. Your suggestion maybe effecient for few cell arrays. However, I want to generalize the code so that it can handle many cell array, say, > 20 cell arrays. I dont think it is a godd practice to do as following
row = [dd{1}', dd{2}', dd{3}', dd{4}', dd{5}', dd{6}', dd{7}', dd{8}', dd{9}', dd{10}', dd{11}', dd{12}', dd{13}', dd{14}', dd{15}', dd{16}', dd{17}', dd{18}', dd{19}', dd{20}'];

Sign in to comment.


Akira Agata
Akira Agata on 3 Aug 2017
How about using cellfun and horzcat functions as follows. In this code, each element in cell array dd is transposed by cellfun. Next, horzcat concatenate each element horizontally.
dd = {[49;50;51;52;53;54], [55;56;57], [85;86;87;88;89;90]};
ddTrans = cellfun(@transpose,dd,'UniformOutput',false);
Output = horzcat(ddTrans{:});

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!