how to get/obtain a specific column of a cell array

23 次查看(过去 30 天)
Hi,
I have the following code, that transforms a 3D array into a cell array. This code was already suggested on the thead: how to convert a 3D array into a n 2D arrays - (mathworks.com)
A=rand(20,1000,30);
for i = 1:20
B{i} = squeeze(A(i,:,:));
end
the dimension of B is 20 cells of dimension 1000*30 each
I would like to select/get/obtain the column 1, 4 and 5 of each cell (currently 30). How would I do it?
I thank you in advance,
Best regards,

采纳的回答

Jan
Jan 2022-3-7
编辑:Jan 2022-3-7
While this is trivial using the original numerical matrix, it is a mess using cells. This shows, that for your problem the decision to use cell is a bad choice.
At least it works:
A = rand(20,1000,30);
B = cell(1, 20); % Pre-allocate for speed!
for i = 1:20
B{i} = squeeze(A(i,:,:));
end
B{3}(:, [1,4,5])
To do this for all elements of the cell array, use a loop. It works with cellfun also, but it is slower and worse to read.
  2 个评论
Hugo
Hugo 2022-3-7
Hi,
Thank you such much for the swift and accurate reply. The problem is that I would like to use matlab functions that do not support 3D arrays. Is there an easier way to transform a 20*1000*30 in 20 arrays of dimensions 1000*30 ? As you can see, I am using squeeze, but I have problems using the resultant cell array in posterior operations.
Jan
Jan 2022-3-7
Why do you want to split the compact and efficient array into elements of a cell? What is the benefit of B{i} compared to A(i, :, :)? If you stay at the original array, the solution would be: A(:, :, [1,4,5]).
By the way, storing 20 matrices might be more efficiently, if you stack them along the 3rd dimension, e.g. as
A = rand(1000, 30, 20);
Then A(:, :, i) is a 2D matrix automatically without calling squeeze, because Matlab let trailing dimensions of size 1 vanish automagically.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by