how to get/obtain a specific column of a cell array
조회 수: 30 (최근 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!