Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linear system of equations with Casadi: A\b #3681

Open
jtorde opened this issue Apr 30, 2024 · 1 comment
Open

Linear system of equations with Casadi: A\b #3681

jtorde opened this issue Apr 30, 2024 · 1 comment

Comments

@jtorde
Copy link

jtorde commented Apr 30, 2024

In the Python API of Casadi, is there any equivalent to the A\b command of Matlab? This is what I tried

from casadi import *
A = DM([[1.0,3.0,5.0],[2.0,4.0,1.0]]) #A is 2x3
b = DM([[1.0],[5.0]])                 #b is 2x1
solve(A,b)  #Fails with Assertion "a.size1() == a.size2()" failed: solve: A not square but 2x3
solve(A,b,"lapackqr") #Fails with Segmentation fault (core dumped)
solve(A,b,"lapacklu") #Return [-nan, inf]
solve(A,b,"lsqr") #Returns [0.636364, 1.07487] Why does it have only 2 elements instead of 3?
solve(A,b,"ma27") #Return [-0.338028, 1.69014] Why does it have only 2 elements instead of 3?

In Matlab this works as follows:

A = [1 3 5;
     2 4 1];
b = [1;5];
A\b  %It returns [0    1.4118    -0.6471]'

I read the examples at https://github.com/casadi/casadi/blob/main/test/python/linearsolver.py but couldn't find the solution

Thanks!

@jaeandersson
Copy link
Member

The linear solvers might not handle non-square systems well. For overdetermined systems, you should be able to solve the normal equations. For underdetermined systems, maybe use QR:

import casadi as ca
A = ca.DM([[1.0,3.0,5.0],[2.0,4.0,1.0]]) #A is 2x3
b = ca.DM([[1.0],[5.0]])                 #b is 2x1
# Underdetermined system of equation, QR factorization of A transpose
Q, R = ca.qr(A.T)
# A*x = b <=> R.T*Q.T*x = b
x = ca.mtimes(Q, ca.solve(R.T, b))
x  # least-squares solution

Alternatively, consider reformulating your problem so that you don't get an underdetermined system of equations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants