MATLAB: Report a MATLAB problem (calling cell as {A{i}} being faster than A(I))

cell arrayswrite faster code

MATLAB says that "{A{I}} can usually be replaced by A(I) or A(I)', which can be much faster."
but you can see in the following example that it's 5 times slower!
%----------- example ----------------
a = randi(255,100,100,100);
[s1,s2,s3] = size(a);
a2 = cell(s3);
for k=1:s3
a2{k} = a(:,:,k);
end
%--------------- (1) faster ------------
tic
for t = 1:1
for i = 1:s1
for j=1:s2
for k=1:s3
b = {a2{k}};
end
end
end
end
toc
%---------------- (2) slower -----------
tic
for t = 1:1
for i = 1:s1
for j=1:s2
for k=1:s3
b = a2(k);
end
end
end
end
toc
%---- Result --------
Elapsed time is 1.188993 seconds.
Elapsed time is 5.511241 seconds.

Best Answer

That is indeed strange.
Note that A(k) makes a lot more sense than {A{k}}. Both create the same thing but conceptually, A(k) just says give the cell at index k whereas {A{k}} says give me the content of the cell at index k and put it into a cell again.
Behind the scenes, both syntaxes have to allocate memory for a 1x1 cell array and then copy the pointer to the matrix contained in the cell, so I don't understand why the massive difference in speed. Only Mathworks can tell us what is actually happening.
At the end of the day, unless the profiler has highlighted that line as a bottleneck, I would go with the A(k) syntax which in my opinion is more appropriate and easier to read.
Note that if you're chasing for performance improvements, your example has two problems that have a lot more impact on speed and memory
  • the allocation of a 100x100 cell array, of which you only use the first column
a2 = cell(s3, 1); %allocate a 100x1 cell array instead of a 100x100 cell array
would be a lot better
  • the copying in a loop of the matrices
a2 = reshape(num2cell(a, [1 2]), [], 1); %num2cell will create a 1x1x100 vector cell array, then reshaped into a column vector.
would eliminate the loop and the need for the preallocation.