function for two numpy array costume multiplication











up vote
0
down vote

favorite












I need a simple numpy function do this multiplication without a for-loop and more time efficient.



Actually I want a function that multiplies each row of a to b



a=np.arange(2,12).reshape(5,2)
b=np.array([[1,2],[3,4]])
c=np.array([[a[i,:]@b] for i in range(a.shape[0])])









share|improve this question




























    up vote
    0
    down vote

    favorite












    I need a simple numpy function do this multiplication without a for-loop and more time efficient.



    Actually I want a function that multiplies each row of a to b



    a=np.arange(2,12).reshape(5,2)
    b=np.array([[1,2],[3,4]])
    c=np.array([[a[i,:]@b] for i in range(a.shape[0])])









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I need a simple numpy function do this multiplication without a for-loop and more time efficient.



      Actually I want a function that multiplies each row of a to b



      a=np.arange(2,12).reshape(5,2)
      b=np.array([[1,2],[3,4]])
      c=np.array([[a[i,:]@b] for i in range(a.shape[0])])









      share|improve this question















      I need a simple numpy function do this multiplication without a for-loop and more time efficient.



      Actually I want a function that multiplies each row of a to b



      a=np.arange(2,12).reshape(5,2)
      b=np.array([[1,2],[3,4]])
      c=np.array([[a[i,:]@b] for i in range(a.shape[0])])






      python numpy matrix-multiplication multiplying numpy-ndarray






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 7 at 15:06









      blue-phoenox

      3,10181438




      3,10181438










      asked Nov 7 at 14:16









      user10482281

      32




      32
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          With numpy.tensordot:



          c = np.tensordot(a, b, axes=1)


          If you insist that shape will be the same:



          c.reshape(5,1,2)





          share|improve this answer





















          • that returns exactly what i want
            – user10482281
            Nov 7 at 14:48






          • 1




            This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
            – Matt Pitkin
            Nov 7 at 14:51










          • @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
            – dobkind
            Nov 7 at 14:57


















          up vote
          1
          down vote













          Using numpy einsum you could do (edited to reshape the array based on @dobkind's answer):



          c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)


          which should be faster.



          %timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
          1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


          versus (using the @ matrix multiplication operator, which works in Python 3)



          %timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
          10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)





          share|improve this answer























          • I run your suggestion but it's answer is not as same as what I want
            – user10482281
            Nov 7 at 14:38










          • Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
            – Matt Pitkin
            Nov 7 at 14:44




















          up vote
          1
          down vote













          To use @, make a a 3d array (5,1,2) with pairs well with (2,2) (or (1,2,2) by automatic broadcasting).



          In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
          Out[448]:
          array([[[11, 16]],

          [[19, 28]],

          [[27, 40]],

          [[35, 52]],

          [[43, 64]]])

          In [450]: a[:,None,:]@b
          Out[450]:
          array([[[11, 16]],

          [[19, 28]],

          [[27, 40]],

          [[35, 52]],

          [[43, 64]]])


          This is actually a bit faster than the einsum solution - though with a example this small I wouldn't make a big deal about timings.






          share|improve this answer




























            up vote
            0
            down vote













            Use matmul function from numpy to multiply two matrices.
            Let me know whether this helps. Thank you.



            c = np.matmul(a,b)





            share|improve this answer





















            • I really appreciate your cooperation but this is not work for my application
              – user10482281
              Nov 7 at 14:36










            • also @ is matmul
              – user10482281
              Nov 7 at 14:38











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53191256%2ffunction-for-two-numpy-array-costume-multiplication%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            With numpy.tensordot:



            c = np.tensordot(a, b, axes=1)


            If you insist that shape will be the same:



            c.reshape(5,1,2)





            share|improve this answer





















            • that returns exactly what i want
              – user10482281
              Nov 7 at 14:48






            • 1




              This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
              – Matt Pitkin
              Nov 7 at 14:51










            • @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
              – dobkind
              Nov 7 at 14:57















            up vote
            1
            down vote



            accepted










            With numpy.tensordot:



            c = np.tensordot(a, b, axes=1)


            If you insist that shape will be the same:



            c.reshape(5,1,2)





            share|improve this answer





















            • that returns exactly what i want
              – user10482281
              Nov 7 at 14:48






            • 1




              This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
              – Matt Pitkin
              Nov 7 at 14:51










            • @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
              – dobkind
              Nov 7 at 14:57













            up vote
            1
            down vote



            accepted







            up vote
            1
            down vote



            accepted






            With numpy.tensordot:



            c = np.tensordot(a, b, axes=1)


            If you insist that shape will be the same:



            c.reshape(5,1,2)





            share|improve this answer












            With numpy.tensordot:



            c = np.tensordot(a, b, axes=1)


            If you insist that shape will be the same:



            c.reshape(5,1,2)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 7 at 14:42









            dobkind

            28616




            28616












            • that returns exactly what i want
              – user10482281
              Nov 7 at 14:48






            • 1




              This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
              – Matt Pitkin
              Nov 7 at 14:51










            • @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
              – dobkind
              Nov 7 at 14:57


















            • that returns exactly what i want
              – user10482281
              Nov 7 at 14:48






            • 1




              This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
              – Matt Pitkin
              Nov 7 at 14:51










            • @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
              – dobkind
              Nov 7 at 14:57
















            that returns exactly what i want
            – user10482281
            Nov 7 at 14:48




            that returns exactly what i want
            – user10482281
            Nov 7 at 14:48




            1




            1




            This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
            – Matt Pitkin
            Nov 7 at 14:51




            This is definitely the neatest answer, but note that tensordot is about 10 times slower (on my machine at least) than using einsum. It also seem to be a bit slower than the OPs original method.
            – Matt Pitkin
            Nov 7 at 14:51












            @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
            – dobkind
            Nov 7 at 14:57




            @MattPitkin Thank you for your interesting insight. I personally still find it difficult to understand how einsum works. Glad to see that both answers appear.
            – dobkind
            Nov 7 at 14:57












            up vote
            1
            down vote













            Using numpy einsum you could do (edited to reshape the array based on @dobkind's answer):



            c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)


            which should be faster.



            %timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
            1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


            versus (using the @ matrix multiplication operator, which works in Python 3)



            %timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
            10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)





            share|improve this answer























            • I run your suggestion but it's answer is not as same as what I want
              – user10482281
              Nov 7 at 14:38










            • Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
              – Matt Pitkin
              Nov 7 at 14:44

















            up vote
            1
            down vote













            Using numpy einsum you could do (edited to reshape the array based on @dobkind's answer):



            c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)


            which should be faster.



            %timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
            1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


            versus (using the @ matrix multiplication operator, which works in Python 3)



            %timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
            10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)





            share|improve this answer























            • I run your suggestion but it's answer is not as same as what I want
              – user10482281
              Nov 7 at 14:38










            • Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
              – Matt Pitkin
              Nov 7 at 14:44















            up vote
            1
            down vote










            up vote
            1
            down vote









            Using numpy einsum you could do (edited to reshape the array based on @dobkind's answer):



            c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)


            which should be faster.



            %timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
            1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


            versus (using the @ matrix multiplication operator, which works in Python 3)



            %timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
            10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)





            share|improve this answer














            Using numpy einsum you could do (edited to reshape the array based on @dobkind's answer):



            c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)


            which should be faster.



            %timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
            1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


            versus (using the @ matrix multiplication operator, which works in Python 3)



            %timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
            10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 7 at 15:35

























            answered Nov 7 at 14:33









            Matt Pitkin

            463312




            463312












            • I run your suggestion but it's answer is not as same as what I want
              – user10482281
              Nov 7 at 14:38










            • Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
              – Matt Pitkin
              Nov 7 at 14:44




















            • I run your suggestion but it's answer is not as same as what I want
              – user10482281
              Nov 7 at 14:38










            • Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
              – Matt Pitkin
              Nov 7 at 14:44


















            I run your suggestion but it's answer is not as same as what I want
            – user10482281
            Nov 7 at 14:38




            I run your suggestion but it's answer is not as same as what I want
            – user10482281
            Nov 7 at 14:38












            Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
            – Matt Pitkin
            Nov 7 at 14:44






            Try np.einsum('ki,ij->kj', a, b) - I've edited the answer to this option. Also @dobkind's answer works.
            – Matt Pitkin
            Nov 7 at 14:44












            up vote
            1
            down vote













            To use @, make a a 3d array (5,1,2) with pairs well with (2,2) (or (1,2,2) by automatic broadcasting).



            In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
            Out[448]:
            array([[[11, 16]],

            [[19, 28]],

            [[27, 40]],

            [[35, 52]],

            [[43, 64]]])

            In [450]: a[:,None,:]@b
            Out[450]:
            array([[[11, 16]],

            [[19, 28]],

            [[27, 40]],

            [[35, 52]],

            [[43, 64]]])


            This is actually a bit faster than the einsum solution - though with a example this small I wouldn't make a big deal about timings.






            share|improve this answer

























              up vote
              1
              down vote













              To use @, make a a 3d array (5,1,2) with pairs well with (2,2) (or (1,2,2) by automatic broadcasting).



              In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
              Out[448]:
              array([[[11, 16]],

              [[19, 28]],

              [[27, 40]],

              [[35, 52]],

              [[43, 64]]])

              In [450]: a[:,None,:]@b
              Out[450]:
              array([[[11, 16]],

              [[19, 28]],

              [[27, 40]],

              [[35, 52]],

              [[43, 64]]])


              This is actually a bit faster than the einsum solution - though with a example this small I wouldn't make a big deal about timings.






              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote









                To use @, make a a 3d array (5,1,2) with pairs well with (2,2) (or (1,2,2) by automatic broadcasting).



                In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
                Out[448]:
                array([[[11, 16]],

                [[19, 28]],

                [[27, 40]],

                [[35, 52]],

                [[43, 64]]])

                In [450]: a[:,None,:]@b
                Out[450]:
                array([[[11, 16]],

                [[19, 28]],

                [[27, 40]],

                [[35, 52]],

                [[43, 64]]])


                This is actually a bit faster than the einsum solution - though with a example this small I wouldn't make a big deal about timings.






                share|improve this answer












                To use @, make a a 3d array (5,1,2) with pairs well with (2,2) (or (1,2,2) by automatic broadcasting).



                In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
                Out[448]:
                array([[[11, 16]],

                [[19, 28]],

                [[27, 40]],

                [[35, 52]],

                [[43, 64]]])

                In [450]: a[:,None,:]@b
                Out[450]:
                array([[[11, 16]],

                [[19, 28]],

                [[27, 40]],

                [[35, 52]],

                [[43, 64]]])


                This is actually a bit faster than the einsum solution - though with a example this small I wouldn't make a big deal about timings.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 7 at 16:20









                hpaulj

                108k673137




                108k673137






















                    up vote
                    0
                    down vote













                    Use matmul function from numpy to multiply two matrices.
                    Let me know whether this helps. Thank you.



                    c = np.matmul(a,b)





                    share|improve this answer





















                    • I really appreciate your cooperation but this is not work for my application
                      – user10482281
                      Nov 7 at 14:36










                    • also @ is matmul
                      – user10482281
                      Nov 7 at 14:38















                    up vote
                    0
                    down vote













                    Use matmul function from numpy to multiply two matrices.
                    Let me know whether this helps. Thank you.



                    c = np.matmul(a,b)





                    share|improve this answer





















                    • I really appreciate your cooperation but this is not work for my application
                      – user10482281
                      Nov 7 at 14:36










                    • also @ is matmul
                      – user10482281
                      Nov 7 at 14:38













                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    Use matmul function from numpy to multiply two matrices.
                    Let me know whether this helps. Thank you.



                    c = np.matmul(a,b)





                    share|improve this answer












                    Use matmul function from numpy to multiply two matrices.
                    Let me know whether this helps. Thank you.



                    c = np.matmul(a,b)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 7 at 14:29









                    Adrish

                    566




                    566












                    • I really appreciate your cooperation but this is not work for my application
                      – user10482281
                      Nov 7 at 14:36










                    • also @ is matmul
                      – user10482281
                      Nov 7 at 14:38


















                    • I really appreciate your cooperation but this is not work for my application
                      – user10482281
                      Nov 7 at 14:36










                    • also @ is matmul
                      – user10482281
                      Nov 7 at 14:38
















                    I really appreciate your cooperation but this is not work for my application
                    – user10482281
                    Nov 7 at 14:36




                    I really appreciate your cooperation but this is not work for my application
                    – user10482281
                    Nov 7 at 14:36












                    also @ is matmul
                    – user10482281
                    Nov 7 at 14:38




                    also @ is matmul
                    – user10482281
                    Nov 7 at 14:38


















                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53191256%2ffunction-for-two-numpy-array-costume-multiplication%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Tangent Lines Diagram Along Smooth Curve

                    Yusuf al-Mu'taman ibn Hud

                    Zucchini