0

I have a 3D matrix (8x5x100) containing numerical data. I need to pass a 2D matrix (8x5) taken from the 3D matrix into another function and repeat this process 100 times(length of 3D matrix). My goal is to speed up this process as much as possible. Sorry, I cannot post my actual code.

Current code:

3dmatrix=ones(8,5,100);
for i=1:100
    output(i)=subfunction(3dmatrix(:,:,i));
end

I read about using arrayfun which may be faster than looping. Is this the correct implementation?

3dmatrix=ones(8,5,100); 
for i=1:100
    output(i)=arrayfun(@(x) subfunction(x),3dmatrix(:,:,i));
end

When I try to execute the code using this new method, I keep getting errors in my "subfunction" code. In "subfunction", it uses the size of the 2D matrix for its calculations. However, when I use the arrayfun method, it keeps reading the size as a 1x1 instead of 8x5, causing the rest of my code to crash, complaining about not being able to access certain parts of vectors since they are not calculated due to the size discrepancy. Am I passing in the matrix correctly?

What is the correct way of going about this with speed being imperative? Thanks!

  • `arrayfun` is probably [_slower_](http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why) than looping. To gain speed you could perhaps _vectorize_ (possibly with `bsxfun`). But whether that can be done or not highly _depends on your function_, which you haven't posted – Luis Mendo Dec 05 '14 at 23:51

2 Answers2

0

Did you look at the arrayfun documentation? I don't think you need to use the loop when using arrayfun. Also have you considered using parfor loops? You could use them to make your code faster too..

3dmatrix=ones(8,5,100); 
parfor i=1:100
    output(i)=arrayfun(@(x) subfunction(x),3dmatrix(:,:,i));
end
sleeping_dragon
  • 701
  • 1
  • 10
  • 27
0

From the Matlab docs for arrayfun it says,

Apply function to each element of array

That is why your function is receiving a 1x1 element. If you want to use arrayfun the way you are using it you would need to convert the 3d matrix into a cell array of 2d matrices.

2dmatrix=ones(8,5);
3dmatrix=cell(1,100);
3dmatrix(:)={2dmatrix};
output = arrayfun(@subfunction,3dmatrix);

Is this any faster than using for loops? I don't know. You would need to actually check this. This is easily done with the tic toc Matlab calls. The slowest part of this is converting the 3d matrix to a cell array, but this might be easily changed in the code depending on how it is structured.

ibezito
  • 5,782
  • 2
  • 22
  • 46
Kassym Dorsel
  • 4,773
  • 1
  • 25
  • 52