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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by