How to remove (or reshape) singleton dimensions in cell array?
14 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 8 Feb 2021
Edited: Jan
on 8 Feb 2021
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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!