Mohammad Saad
Mohammad Saad

Reputation: 2005

How to find least-squares solution to a linear matrix equation in Julia?

I would like to know if there is an alternate function for numpy.linalg.lstsq() in Julia. The function returns a least-squares solution to a linear matrix equation. the correct syntax to access elements from NumPy stack ?

Python Example:

import numpy as np
A = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(A, y, rcond=None)[0]
m, c
(1.0 -0.95) # may vary

Output Chart:

enter image description here

Python Reference: https://numpy.org/doc/stable/reference/generated/numpy.linalg.lstsq.html

Upvotes: 2

Views: 1567

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69899

In this case you can just use \ from Julia Base:

julia> A = [rand(10) ones(10)]
10×2 Matrix{Float64}:
 0.637746  1.0
 0.296172  1.0
 0.795938  1.0
 0.611058  1.0
 0.737017  1.0
 0.992014  1.0
 0.914031  1.0
 0.522682  1.0
 0.3607    1.0
 0.934141  1.0

julia> y = A * [1, -1] + rand(10) ./ 10
10-element Vector{Float64}:
 -0.34049611405598046
 -0.6368145973747783
 -0.10597203750574954
 -0.2950574213524233
 -0.19571807260629853
  0.020902316863572645
 -0.07310077005612584
 -0.40758393396440784
 -0.6137424837773662
 -0.05149257027230776

julia> A \ y
2-element Vector{Float64}:
  0.9582937347300398
 -0.9216908912065571

Upvotes: 2

Related Questions