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

1 次查看(过去 30 天)
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

采纳的回答

balandong
balandong 2017-8-3
编辑:balandong 2017-8-3
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.

更多回答(2 个)

Sanjay Nair
Sanjay Nair 2017-8-2
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 个评论
balandong
balandong 2017-8-3
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}'];

请先登录,再进行评论。


Akira Agata
Akira Agata 2017-8-3
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{:});

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by