High dimensional matrices may indeed be slow to work with sometimes. I will show this comparing the speed of a 2D matrix and your matrix. The matrices will have approximately the same size.
m = function fRef1()
m = rand(5000,10000); % Generate an unsorted matrix to ensure worst case behaviour
end
Running the timeit
function,
timeit(@fRef1,1)
The matrix generation takes 0.7058s for the 2D matrix
m = function fRef2()
m=rand(10,10,10,10,5,10,10,10);
end
timeit(fRef2,1)
And for the 8D matrix it takes 0.7277s which is about the same speed.
Now test to do a simple matrix operation
function M = f1()
m = rand(5000,10000);
M = m.^2.*m+m;
end
Which with timeit
takes 0.9449s. Using the result from fRef1
you can see the matrix operation takes about 0.24s.
Now compare to the 8D matrix
function M = f2()
m = rand(10,10,10,10,5,10,10,10);
M = m.^2.*m+m;
end
which with timeit
takes 1.2553s. Removing the time from fRef2
you will get the time for the matrix operation. The calculation time is then 0.5276s which is about twize the time for the 2D matrix. So can we do better? The answer is yes! Since the operations are done elementwise, the operation is independent on the shape of the matrix. Let us then modify the matrix to a for that Matlab finds more suitable.
function M=f3()
m=rand(10,10,10,10,5,10,10,10);
m=m(:); % Create a row vector
M=m.^2.*m+m;
M = reshape(M,10,10,10,10,5,10,10,10); % reshape the matrix again to
% its original shape
end
timeit
gives us a result of 0.9494s. Which, by removing the time for the creation of m
gives us a result of 0.2217s which is about the same time as of the 2D matrix.
Windows 7, intel core i5-2540M, 2.60GHz, Matlab 2014b