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

34 ビュー (過去 30 日間)
Hugo
Hugo 2022 年 3 月 7 日
編集済み: Jan 2022 年 3 月 7 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by