How could I subtract a 1xN eigen matrix from a MxN matrix, like numpy does?












0















I could not summarize a 1xN matrix from a MxN matrix like I do in numpy.



I create a matrix of np.arange(9).reshape(3,3) with eigen like this:



int buf[9];
for (int i{0}; i < 9; ++i) {
buf[i] = i;
}
m = Map<MatrixXi>(buf, 3,3);


Then I compute mean along row direction:



    m2 = m.rowwise().mean();


I would like to broadcast m2 to 3x3 matrix, and subtract it from m, how could I do this?










share|improve this question





























    0















    I could not summarize a 1xN matrix from a MxN matrix like I do in numpy.



    I create a matrix of np.arange(9).reshape(3,3) with eigen like this:



    int buf[9];
    for (int i{0}; i < 9; ++i) {
    buf[i] = i;
    }
    m = Map<MatrixXi>(buf, 3,3);


    Then I compute mean along row direction:



        m2 = m.rowwise().mean();


    I would like to broadcast m2 to 3x3 matrix, and subtract it from m, how could I do this?










    share|improve this question



























      0












      0








      0








      I could not summarize a 1xN matrix from a MxN matrix like I do in numpy.



      I create a matrix of np.arange(9).reshape(3,3) with eigen like this:



      int buf[9];
      for (int i{0}; i < 9; ++i) {
      buf[i] = i;
      }
      m = Map<MatrixXi>(buf, 3,3);


      Then I compute mean along row direction:



          m2 = m.rowwise().mean();


      I would like to broadcast m2 to 3x3 matrix, and subtract it from m, how could I do this?










      share|improve this question
















      I could not summarize a 1xN matrix from a MxN matrix like I do in numpy.



      I create a matrix of np.arange(9).reshape(3,3) with eigen like this:



      int buf[9];
      for (int i{0}; i < 9; ++i) {
      buf[i] = i;
      }
      m = Map<MatrixXi>(buf, 3,3);


      Then I compute mean along row direction:



          m2 = m.rowwise().mean();


      I would like to broadcast m2 to 3x3 matrix, and subtract it from m, how could I do this?







      c++ eigen






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 3 at 11:37









      Matthieu Brucher

      16.9k32244




      16.9k32244










      asked Jan 3 at 11:32









      coin cheungcoin cheung

      1347




      1347
























          3 Answers
          3






          active

          oldest

          votes


















          2














          You need to use appropriate types for your values, MatrixXi lacks the vector operations (such as broadcasting). You also seem to have the bad habit of declaring your variables well before you initialise them. Don't.



          This should work



          std::array<int, 9> buf;
          std::iota(buf.begin(), buf.end(), 0);

          auto m = Map<Matrix3i>(buf.data());
          auto v = m.rowwise().mean();
          auto result = m.colwise() - v;





          share|improve this answer

































            3














            There is no numpy-like broadcasting available in Eigen, what you can do is reuse the same pattern that you used:



            m.colwise() -= m2


            (See Eigen tutorial on this)



            N.B.: m2 needs to be a vector, not a matrix. Also the more fixed the dimensions, the better the compiler can generate efficient code.






            share|improve this answer


























            • I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

              – coin cheung
              Jan 3 at 11:51











            • It seems we cannot let one matrix minus another matrix, when they have different shapes.

              – coin cheung
              Jan 3 at 11:52






            • 1





              Did you use -= or -?

              – Matthieu Brucher
              Jan 3 at 12:01











            • I see no difference here actually.

              – coin cheung
              Jan 3 at 12:22






            • 1





              @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

              – Caleth
              Jan 3 at 12:36





















            0














            While the .colwise() method already suggested should be preferred in this case, it is actually also possible to broadcast a vector to multiple columns using the replicate method.



            m -= m2.replicate<1,3>();
            // or
            m -= m2.rowwise().replicate<3>();


            If 3 is not known at compile time, you can write



            m -= m2.rowwise().replicate(m.cols());





            share|improve this answer























              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',
              autoActivateHeartbeat: false,
              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%2f54021457%2fhow-could-i-subtract-a-1xn-eigen-matrix-from-a-mxn-matrix-like-numpy-does%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              You need to use appropriate types for your values, MatrixXi lacks the vector operations (such as broadcasting). You also seem to have the bad habit of declaring your variables well before you initialise them. Don't.



              This should work



              std::array<int, 9> buf;
              std::iota(buf.begin(), buf.end(), 0);

              auto m = Map<Matrix3i>(buf.data());
              auto v = m.rowwise().mean();
              auto result = m.colwise() - v;





              share|improve this answer






























                2














                You need to use appropriate types for your values, MatrixXi lacks the vector operations (such as broadcasting). You also seem to have the bad habit of declaring your variables well before you initialise them. Don't.



                This should work



                std::array<int, 9> buf;
                std::iota(buf.begin(), buf.end(), 0);

                auto m = Map<Matrix3i>(buf.data());
                auto v = m.rowwise().mean();
                auto result = m.colwise() - v;





                share|improve this answer




























                  2












                  2








                  2







                  You need to use appropriate types for your values, MatrixXi lacks the vector operations (such as broadcasting). You also seem to have the bad habit of declaring your variables well before you initialise them. Don't.



                  This should work



                  std::array<int, 9> buf;
                  std::iota(buf.begin(), buf.end(), 0);

                  auto m = Map<Matrix3i>(buf.data());
                  auto v = m.rowwise().mean();
                  auto result = m.colwise() - v;





                  share|improve this answer















                  You need to use appropriate types for your values, MatrixXi lacks the vector operations (such as broadcasting). You also seem to have the bad habit of declaring your variables well before you initialise them. Don't.



                  This should work



                  std::array<int, 9> buf;
                  std::iota(buf.begin(), buf.end(), 0);

                  auto m = Map<Matrix3i>(buf.data());
                  auto v = m.rowwise().mean();
                  auto result = m.colwise() - v;






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 3 at 13:38

























                  answered Jan 3 at 12:43









                  CalethCaleth

                  18.5k22142




                  18.5k22142

























                      3














                      There is no numpy-like broadcasting available in Eigen, what you can do is reuse the same pattern that you used:



                      m.colwise() -= m2


                      (See Eigen tutorial on this)



                      N.B.: m2 needs to be a vector, not a matrix. Also the more fixed the dimensions, the better the compiler can generate efficient code.






                      share|improve this answer


























                      • I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

                        – coin cheung
                        Jan 3 at 11:51











                      • It seems we cannot let one matrix minus another matrix, when they have different shapes.

                        – coin cheung
                        Jan 3 at 11:52






                      • 1





                        Did you use -= or -?

                        – Matthieu Brucher
                        Jan 3 at 12:01











                      • I see no difference here actually.

                        – coin cheung
                        Jan 3 at 12:22






                      • 1





                        @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

                        – Caleth
                        Jan 3 at 12:36


















                      3














                      There is no numpy-like broadcasting available in Eigen, what you can do is reuse the same pattern that you used:



                      m.colwise() -= m2


                      (See Eigen tutorial on this)



                      N.B.: m2 needs to be a vector, not a matrix. Also the more fixed the dimensions, the better the compiler can generate efficient code.






                      share|improve this answer


























                      • I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

                        – coin cheung
                        Jan 3 at 11:51











                      • It seems we cannot let one matrix minus another matrix, when they have different shapes.

                        – coin cheung
                        Jan 3 at 11:52






                      • 1





                        Did you use -= or -?

                        – Matthieu Brucher
                        Jan 3 at 12:01











                      • I see no difference here actually.

                        – coin cheung
                        Jan 3 at 12:22






                      • 1





                        @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

                        – Caleth
                        Jan 3 at 12:36
















                      3












                      3








                      3







                      There is no numpy-like broadcasting available in Eigen, what you can do is reuse the same pattern that you used:



                      m.colwise() -= m2


                      (See Eigen tutorial on this)



                      N.B.: m2 needs to be a vector, not a matrix. Also the more fixed the dimensions, the better the compiler can generate efficient code.






                      share|improve this answer















                      There is no numpy-like broadcasting available in Eigen, what you can do is reuse the same pattern that you used:



                      m.colwise() -= m2


                      (See Eigen tutorial on this)



                      N.B.: m2 needs to be a vector, not a matrix. Also the more fixed the dimensions, the better the compiler can generate efficient code.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 3 at 13:46

























                      answered Jan 3 at 11:42









                      Matthieu BrucherMatthieu Brucher

                      16.9k32244




                      16.9k32244













                      • I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

                        – coin cheung
                        Jan 3 at 11:51











                      • It seems we cannot let one matrix minus another matrix, when they have different shapes.

                        – coin cheung
                        Jan 3 at 11:52






                      • 1





                        Did you use -= or -?

                        – Matthieu Brucher
                        Jan 3 at 12:01











                      • I see no difference here actually.

                        – coin cheung
                        Jan 3 at 12:22






                      • 1





                        @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

                        – Caleth
                        Jan 3 at 12:36





















                      • I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

                        – coin cheung
                        Jan 3 at 11:51











                      • It seems we cannot let one matrix minus another matrix, when they have different shapes.

                        – coin cheung
                        Jan 3 at 11:52






                      • 1





                        Did you use -= or -?

                        – Matthieu Brucher
                        Jan 3 at 12:01











                      • I see no difference here actually.

                        – coin cheung
                        Jan 3 at 12:22






                      • 1





                        @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

                        – Caleth
                        Jan 3 at 12:36



















                      I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

                      – coin cheung
                      Jan 3 at 11:51





                      I do m.rowwise() - m2, but only got the error of ** static assertion failed: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)**.

                      – coin cheung
                      Jan 3 at 11:51













                      It seems we cannot let one matrix minus another matrix, when they have different shapes.

                      – coin cheung
                      Jan 3 at 11:52





                      It seems we cannot let one matrix minus another matrix, when they have different shapes.

                      – coin cheung
                      Jan 3 at 11:52




                      1




                      1





                      Did you use -= or -?

                      – Matthieu Brucher
                      Jan 3 at 12:01





                      Did you use -= or -?

                      – Matthieu Brucher
                      Jan 3 at 12:01













                      I see no difference here actually.

                      – coin cheung
                      Jan 3 at 12:22





                      I see no difference here actually.

                      – coin cheung
                      Jan 3 at 12:22




                      1




                      1





                      @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

                      – Caleth
                      Jan 3 at 12:36







                      @coincheung what is the type of m2? it can't be (an alias for) Matrix<int, Dynamic, Dynamic>, it has to be Matrix<int, 1, /*N or Dynamic*/>

                      – Caleth
                      Jan 3 at 12:36













                      0














                      While the .colwise() method already suggested should be preferred in this case, it is actually also possible to broadcast a vector to multiple columns using the replicate method.



                      m -= m2.replicate<1,3>();
                      // or
                      m -= m2.rowwise().replicate<3>();


                      If 3 is not known at compile time, you can write



                      m -= m2.rowwise().replicate(m.cols());





                      share|improve this answer




























                        0














                        While the .colwise() method already suggested should be preferred in this case, it is actually also possible to broadcast a vector to multiple columns using the replicate method.



                        m -= m2.replicate<1,3>();
                        // or
                        m -= m2.rowwise().replicate<3>();


                        If 3 is not known at compile time, you can write



                        m -= m2.rowwise().replicate(m.cols());





                        share|improve this answer


























                          0












                          0








                          0







                          While the .colwise() method already suggested should be preferred in this case, it is actually also possible to broadcast a vector to multiple columns using the replicate method.



                          m -= m2.replicate<1,3>();
                          // or
                          m -= m2.rowwise().replicate<3>();


                          If 3 is not known at compile time, you can write



                          m -= m2.rowwise().replicate(m.cols());





                          share|improve this answer













                          While the .colwise() method already suggested should be preferred in this case, it is actually also possible to broadcast a vector to multiple columns using the replicate method.



                          m -= m2.replicate<1,3>();
                          // or
                          m -= m2.rowwise().replicate<3>();


                          If 3 is not known at compile time, you can write



                          m -= m2.rowwise().replicate(m.cols());






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 9 at 14:36









                          chtzchtz

                          7,61411235




                          7,61411235






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54021457%2fhow-could-i-subtract-a-1xn-eigen-matrix-from-a-mxn-matrix-like-numpy-does%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







                              Popular posts from this blog

                              Monofisismo

                              Angular Downloading a file using contenturl with Basic Authentication

                              Olmecas