how to get/obtain a specific column of a cell array
29 次查看(过去 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,
0 个评论
采纳的回答
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 个评论
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!