Matrix Division in Eigen vs MATLAB

Jun 19, 2022 at 8:59pm
I am trying to find the equivalent of the opertaor in MATLAB:
 
A = B/C

where here A,B, and C are all square matrices with say N-by-N .

So I have the following C++ code where I tried using Eigen but I am not getting correct results:
1
2
3
4
5
6
7
8
9
10
11
Eigen::Matrix< double, (ny+1), (ny+1)> A; //same initialization for B and C

	for (int i = 0; i < ny+1; i++){
		for (int j = 0; j < ny+1; j++){
                C(j + (ny+1)*i) = cos(acos(ygl[j]) *(i));
		B(0,j) = -1. * pow(-1,(j))*(pow(j,2));//replace 1st row with expression
		B((ny),j) =  1. * pow(j,2);//replace last row
		A(j + (ny+1)*i) = (B(j + (ny+1)*i))/(C(j + (ny+1)*i));
		}
	}
	std::cout << A << "\n";


Is matrix division done just simply by / with Eigen like MATLAB or is there another way? Thanks
Last edited on Jun 19, 2022 at 9:00pm
Jun 19, 2022 at 9:20pm
there really is no such thing as matrix division.
matlab lets you do it and understands that you are using it as a convoluted way to write ax=b (rewritten improperly as x = b/a or b\a or whatever it is, my matlab is a few years behind me)

so in eigen you need to either do the underlying math by hand or use a solver depending on what you think division means. If you think a*b = c, then it may involve an inverse or pseudoinverse.
if you want the solution to a system, then you need to use whatever they provide for that.

Jun 19, 2022 at 11:50pm
I guess I can give an example in MATLAB.

This, in C++ is equivalent to x = A\b in MATLAB:
1
2
	x = A.colPivHouseholderQr().solve(b);

But, I am looking for something equivalent to x = A/b in MATLAB. For example in MATLAB:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
A =

     4    12
     6     8
b =

     6    12
    14     8

>> A/b

    1.1333   -0.2000
    0.5333    0.2000

which is different from:
1
2
3
4
>> A\b

    3.0000         0
   -0.5000    1.0000

So I am trying to calculate x = A/b , the first example.
Jun 20, 2022 at 12:38am
I just solved my issue and the it's basically,
1
2
X=A\B computes X=inv(A)*B.
Y=A/B computes Y=A*inv(B)


so then in C++ with Eigen:
 
x= A* B.inverse();
Jun 20, 2022 at 12:46am
So I am trying to calculate x = A/b , the first example.


This duplicates the output in your first MATLAB example:
1
2
3
4
5
6
7
8
9
10
#include <Eigen/Core>
#include <Eigen/QR>
#include <iostream>

int main() 
{
  Eigen::Matrix2f A { { 4.f, 12.f }, { 6.f,  8.f } }; 
  Eigen::Matrix2f B { { 6.f, 12.f }, { 14.f, 8.f } }; 
  std::cout << B.transpose().colPivHouseholderQr().solve(A.transpose()).transpose();  
}


Could be faster than computing the inverse matrix, but YMMV
Last edited on Jun 20, 2022 at 12:48am
Jun 20, 2022 at 4:40am
@mbozzi
Thanks! This is pretty helpful actually.
Topic archived. No new replies allowed.