How to remove (or reshape) singleton dimensions in cell array?

23 ビュー (過去 30 日間)
Brasco , D.
Brasco , D. 2021 年 2 月 8 日
編集済み: Brasco , D. 2021 年 2 月 8 日
Hi guys,
My question is about reshaping cell elements. Let say I have a cell array, named MyCell, that consist of 5 elements. The size of each element in MyCell array is different. MyCell is like:
MyCell = { [1x1x30 double] ; [1x1x25 double]; [1x1x22 double]; [1x1x34 double]; [1x1x38 double] }
I want to reshape each cell element and make them 2 dimentional like [30x1 double] etc.
MyCell = { [30x1 double] ; [25x1 double]; [22x1 double]; [34x1 double]; [38x1 double] }
Is it possible to do this with out using a for loop?
Is there any indexing tricks that can be used in reshape or squeeze functions ?
thank you guys

採用された回答

Jan
Jan 2021 年 2 月 8 日
編集済み: Jan 2021 年 2 月 8 日
The FOR loop is the simplest and fastest method. I do not see a reason to avoid it. But if you really want to:
C = cellfun(@(x) reshape(x, [], 1), C, 'UniformOutput', 0)
% Faster:
C = cellfun(@(x) x(:), C, 'UniformOutput', 0)
A speed comparison:
nC = 1e5; % Create some test data
C = cell(1, nC);
for k = 1:nC
C{k} = zeros(1, 1, randi(20, 1));
end
tic; % The fastes method: a simple loop
C2 = cell(size(C)); % Pre-allocation!!!
for k = 1:numel(C)
C2{k} = C{k}(:);
end
toc
tic;
C3 = cellfun(@(x) x(:), C, 'UniformOutput', 0);
toc
tic;
C4 = cellfun(@(x) reshape(x, [], 1), C, 'UniformOutput', 0);
toc
% Elapsed time is 0.063954 seconds. Loop
% Elapsed time is 0.440766 seconds. cellfun( x(:))
% Elapsed time is 0.530042 seconds. cellfun( reshape(x))
Note, that vectorization is fast for operations, which operate on vectors. CELLFUN is fast for the "backward compatibility mode" to define the operation by a string. Then Matlab performs the operation inside CELLFUN, while for anonymous functions or function handles this function is evaluated. But this happens in a FOR loop also, so prefer the direct approach.
  1 件のコメント
Brasco , D.
Brasco , D. 2021 年 2 月 8 日
編集済み: Brasco , D. 2021 年 2 月 8 日
Thank you Jan.
I asked this question because i am not very good at logic indexing tricks about matrices and arrays. I just wonder if there is any shortcut to solve this type of problems. My expectations about MATLAB are very high :D
Again thank you for your help. As you advised, I will go with the FOR loop.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by