2

I have an NxN array of 2x2 matrices, and I need to invert each of them. Using Matlab (or user defined functions), is there a way to do this faster than just looping through each one and inverting it? I can assume that they are all invertable and well conditioned.

example:

% dim(A) = 2 x 2 x N x N
I = eye(2);
for i = 1:N
for j = 1:N
    exphl(:, :, i, j) = expm(A(:, :, i, j)); 
    for k = 1:M
        z = r(k); %constants
        zIA = (z*I-A)\I;
        exphL1(:, :, i, j) = exphL1(:, :, i, j) + dt*zIA*(exp(z/2)-1);
    end
end 
end

As a side note, could anyone tell me why the profiler says that the last line "exphL1(:..." takes the most time?

5o3x
  • 41
  • 5
  • 1
    There is a user defined function that does exactly this [link](http://www.mathworks.com/matlabcentral/fileexchange/31222-inversion-every-2d-slice-for-arbitrary-multi-dimension-array/) – 5o3x Dec 03 '14 at 10:04

1 Answers1

-2

There is a MATLAB function to do the job : inv(). It is probably faster than your custom loop.

oro777
  • 1,110
  • 1
  • 14
  • 29
  • 2
    inv() is slower at computing inverses than \ – 5o3x Dec 03 '14 at 08:06
  • see [this thread](http://stackoverflow.com/questions/1419580/why-is-matlabs-inv-slow-and-inaccurate) why you should **NOT** use `inv`. – Shai Dec 03 '14 at 08:15
  • 2
    And if you wonder if the answer to the other question is credible... Loren know what she's talking about! At least better than you, me and almost everyone else. She works on design of the MATLAB-language and has been writing [blog posts about MATLAB](http://blogs.mathworks.com/loren/) since 2005. – Stewie Griffin Dec 03 '14 at 08:57
  • @5o3x: Technically, using `inv` is not always slower in real applications. As you know, the point is that `inv` is calculated differently and will often lead to less accurate results. – horchler Dec 03 '14 at 18:30
  • @horchler in all my experience `inv` increases the time by about 25% – 5o3x Dec 03 '14 at 20:24