Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8400651
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T21:36:45+00:00 2026-06-09T21:36:45+00:00

Normally I would invert an array of 3×3 matrices in a for loop like

  • 0

Normally I would invert an array of 3×3 matrices in a for loop like in the example below. Unfortunately for loops are slow. Is there a faster, more efficient way to do this?

import numpy as np
A = np.random.rand(3,3,100)
Ainv = np.zeros_like(A)
for i in range(100):
    Ainv[:,:,i] = np.linalg.inv(A[:,:,i])
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T21:36:46+00:00Added an answer on June 9, 2026 at 9:36 pm

    It turns out that you’re getting burned two levels down in the numpy.linalg code. If you look at numpy.linalg.inv, you can see it’s just a call to numpy.linalg.solve(A, inv(A.shape[0]). This has the effect of recreating the identity matrix in each iteration of your for loop. Since all your arrays are the same size, that’s a waste of time. Skipping this step by pre-allocating the identity matrix shaves ~20% off the time (fast_inverse). My testing suggests that pre-allocating the array or allocating it from a list of results doesn’t make much difference.

    Look one level deeper and you find the call to the lapack routine, but it’s wrapped in several sanity checks. If you strip all these out and just call lapack in your for loop (since you already know the dimensions of your matrix and maybe know that it’s real, not complex), things run MUCH faster (Note that I’ve made my array larger):

    import numpy as np
    A = np.random.rand(1000,3,3)
    def slow_inverse(A): 
        Ainv = np.zeros_like(A)
    
        for i in range(A.shape[0]):
            Ainv[i] = np.linalg.inv(A[i])
        return Ainv
    
    def fast_inverse(A):
        identity = np.identity(A.shape[2], dtype=A.dtype)
        Ainv = np.zeros_like(A)
    
        for i in range(A.shape[0]):
            Ainv[i] = np.linalg.solve(A[i], identity)
        return Ainv
    
    def fast_inverse2(A):
        identity = np.identity(A.shape[2], dtype=A.dtype)
    
        return array([np.linalg.solve(x, identity) for x in A])
    
    from numpy.linalg import lapack_lite
    lapack_routine = lapack_lite.dgesv
    # Looking one step deeper, we see that solve performs many sanity checks.  
    # Stripping these, we have:
    def faster_inverse(A):
        b = np.identity(A.shape[2], dtype=A.dtype)
    
        n_eq = A.shape[1]
        n_rhs = A.shape[2]
        pivots = zeros(n_eq, np.intc)
        identity  = np.eye(n_eq)
        def lapack_inverse(a):
            b = np.copy(identity)
            pivots = zeros(n_eq, np.intc)
            results = lapack_lite.dgesv(n_eq, n_rhs, a, n_eq, pivots, b, n_eq, 0)
            if results['info'] > 0:
                raise LinAlgError('Singular matrix')
            return b
    
        return array([lapack_inverse(a) for a in A])
    
    
    %timeit -n 20 aI11 = slow_inverse(A)
    %timeit -n 20 aI12 = fast_inverse(A)
    %timeit -n 20 aI13 = fast_inverse2(A)
    %timeit -n 20 aI14 = faster_inverse(A)
    

    The results are impressive:

    20 loops, best of 3: 45.1 ms per loop
    20 loops, best of 3: 38.1 ms per loop
    20 loops, best of 3: 38.9 ms per loop
    20 loops, best of 3: 13.8 ms per loop
    

    EDIT: I didn’t look closely enough at what gets returned in solve. It turns out that the ‘b’ matrix is overwritten and contains the result in the end. This code now gives consistent results.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Normally I would just use URL GET parameters but CodeIgniter doesn't seem to like
Normally I would go: bgwExportGrid.RunWorkerCompleted += ReportManager.RunWorkerCompleted; The ReportManager class is a static class
Normally I would just do this. $str = preg_replace('#(\d+)#', ' $1 ', $str); If
Normally it would be in such a structure: ../application/modules/somemodule/views/scripts/index/index.phtml How I move it to:
Normally I would have one junit test that shows up in my integration server
Normally I would do select top (1) * from table where id active =
This kind of code would normally work in PHP, but since the scope is
I'm trying to develop an app that would normally be considered to be malware,
I have this code that where I would normally use one line: if (tableView
If I have a table of a hundred users normally I would just set

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.