#๐Ÿ”’ Putting Matrices all on One Line

149 messages ยท Page 1 of 1 (latest)

winged prairie
#

Need help with putting all the lines as one and now seperate.

rustic lightBOT
#

@winged prairie

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

winged prairie
#

helpers

#

@helpers

#

@deep belfry please if ou can help me out

deep belfry
winged prairie
#

Yes

#

It is a function call to it

#

Here is the np.array functions

deep belfry
#

i've never worked with np, but if it is to do with python and not np functions im happy to help

winged prairie
#

That is np for python

#

numpy as np

#

@spice juniper

spice juniper
#

What?

deep belfry
#

just taggin random ppl ๐Ÿ˜ญ

winged prairie
#

I need some help with putting all the matrices one line as show in my screenshot

#

@deep belfry he has helped me out in the past

#

row_echelon_M

spice juniper
#

@winged prairie no one is on-call to help you at any time, even if they've helped you in the past. so don't ping people to summon them to your question

winged prairie
#

Do get it

spice juniper
#

and don't post screenshots of text.

#

!code

rustic lightBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

winged prairie
#
def gaussian_elimination(A, B):
    """
    Solve a linear system represented by an augmented matrix using the Gaussian elimination method.

    Parameters:
    - A (numpy.array): Square matrix of size n x n representing the coefficients of the linear system
    - B (numpy.array): Column matrix of size 1 x n representing the constant terms.

    Returns:
    numpy.array or str: The solution vector if a unique solution exists, or a string indicating the type of solution.
    """

    ### START CODE HERE ###
    # Get the matrix in row echelon form
    row_echelon_M = np.linalg.solve(A,B)
    # If the system is non-singular, then perform back substitution to get the result. 
    # Since the function row_echelon_form returns a string if there is no solution, let's check for that.
    # The function isinstance checks if the first argument has the type as the second argument, returning True if it does and False otherwise.
    if not isinstance(row_echelon_M, str):
        return row_echelon_M
    ### END SOLUTION HERE ###
    
    
    return solution
deep belfry
winged prairie
#

If you can show me with the code as justr do the str() then

deep belfry
#

i've never used numpy, i dont know where the list is

winged prairie
#

Okay

#

Do you know somebody who can help me out

deep belfry
winged prairie
#

Okay

split pilot
#

The arrays aren't correct.

winged prairie
#

Then how should they be then

split pilot
#

It should be 1d not 2d.

winged prairie
#

A = np.array([[1,2,3], [3,4,5], [4,5,6]])
B = np.array([[1], [5], [7]])

print(augmented_matrix(A,B))

#

So I am wondering how I can do that

#

@split pilot

split pilot
#

I'm confused. Why is it augmented_matrix now instead of gaussian_elimination?

winged prairie
#

It is a different function call as it does the same idea

#
def augmented_matrix(A, B):
    """
    Create an augmented matrix by horizontally stacking two matrices A and B.

    Parameters:
    - A (numpy.array): First matrix.
    - B (numpy.array): Second matrix.

    Returns:
    - numpy.array: Augmented matrix obtained by horizontally stacking A and B.
    """
    augmented_M = np.hstack((A,B))
    return augmented_M
#

There the code for it but am trying to focus on the gaussian_elimination

split pilot
#

Yes, but augmented_matrix returns an actual 2d array here: 3x4
On the other hand gaussian_elimination returns a 5x1 array when it's supposed to return a vector of length 5.

winged prairie
#

How would you suggest I fix it then

#

Which place then

split pilot
#

You could .ravel() the matrix before returning it.

winged prairie
#

A = np.array([[1,2,3], [3,4,5], [4,5,6]])
B = np.array([[1], [5], [7]]).ravel()

#

Like that

split pilot
#

I think return row_echelon_m.ravel()

winged prairie
#

That worked

#

This took 3 weeks to solve it

#

@split pilot thank you so much and would it be okay I can ask you future help

split pilot
#

I think it makes no sense to ask specific people for help. Better just put your question in a help channel.

winged prairie
#

Okay as thank you

split pilot
winged prairie
#

here was an error grading your submission. Details:
operands could not be broadcast together with shapes (8,) (4,)

#

w2_unittest.test_gaussian_elimination(gaussian_elimination)

#

I am getting this erro from this funciton

split pilot
#

What does that mean?

split pilot
#

In this question on stackoverflow the OP tried to add a 1d array and a 2d array. Of course that's not possible.

#

Do you try to add arrays in gaussian_elimination?

winged prairie
#

No not at all

#
def gaussian_elimination(A, B):
    """
    Solve a linear system represented by an augmented matrix using the Gaussian elimination method.

    Parameters:
    - A (numpy.array): Square matrix of size n x n representing the coefficients of the linear system
    - B (numpy.array): Column matrix of size 1 x n representing the constant terms.

    Returns:
    numpy.array or str: The solution vector if a unique solution exists, or a string indicating the type of solution.
    """
    ### START CODE HERE ###
    # Get the matrix in row echelon form
    row_echelon_M = np.linalg.solve(A, B)
    # If the system is non-singular, then perform back substitution to get the result. 
    # Since the function row_echelon_form returns a string if there is no solution, let's check for that.
    # The function isinstance checks if the first argument has the type as the second argument, returning True if it does and False otherwise.
    if not isinstance(row_echelon_M, str):
        return row_echelon_M.ravel()
    ### END SOLUTION HERE ###
    
    
    return solution
        
#
equations = [
[3, 6, 6, 8, 1],
[5, 3, 6, -10],
[4,- 5,8,8],
[4, 0,0, 0, 8,9]]

variables, A, B = string_to_augmented_matrix(equations)

sols = gaussian_elimination(A, B).split(',')

if not isinstance(sols, str):
    for variable, solution in zip(variables,sols):
        print(f"{variable} = {solution:.4f}")
else:
    print(sols)
#

Sorry as lets solve one at a time

split pilot
#

numpy arrays don't have a split method.

winged prairie
#

Okay

#
from utils import string_to_augmented_matrix
#

There is the from utils

split pilot
#

Interesting. But equations isn't a string.

winged prairie
#

This coming rom a coursera course as no idea why for this error

split pilot
#

I think your equations already are an augmented matrix. Could that be?

winged prairie
#

Probably

split pilot
#

Probably you did something wrong then. Maybe you should find out what this function does.

winged prairie
#

I will

#
equations = [
[3, 6, 6, 8, 1],
[5, 3, 6, -10],
[4,- 5,8,8],
[4, 0,0, 0, 8,9]]

variables, A, B = string_to_augmented_matrix(equations)

sols = gaussian_elimination(A, B)

if not isinstance(sols, str):
    for variable, solution in zip(variables,sols):
        print(f"{variable} = {solution:.4f}")
else:
    print(sols)
#
from utils import string_to_augmented_matrix
#

The code below will allow you to write any equation in the format it is given below (any unknown lower case variables are accepted, in any order) and transform it in its respective augmented matrix so you can solve it using the functions you just wrote in this assignment!
You just need to change the equations variable, always keeping * to indicate product between unknowns and variables and one equation in each line!

split pilot
#

What format is given below?

winged prairie
#
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-40-a6ca3511c2c5> in <module>
      5 [4, 0,0, 0, 8,9]]
      6 
----> 7 variables, A, B = string_to_augmented_matrix(equations)
      8 
      9 sols = gaussian_elimination(A, B)

~/work/utils.py in string_to_augmented_matrix(equations)
      4 def string_to_augmented_matrix(equations):
      5     # Split the input string into individual equations
----> 6     equation_list = equations.split('\n')
      7     equation_list = [x for x in equation_list if x != '']
      8     # Create a list to store the coefficients and constants

AttributeError: 'list' object has no attribute 'split'
#

There is no function defintion

#
variables, A, B = string_to_augmented_matrix(equations)
split pilot
#

Yes, lists don't have a split method.

winged prairie
#

Do know as I think it just the grading system itself is the main issue

#

Can you help me with back subsittuin then

#

!pastebin

rustic lightBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

winged prairie
#

There is the equation itself

#

Expected:
[-0.0841373 0.12363912 0.88135387 -2.83469018 -0.27829698 -3.87730702],
but got:
[-0.30941613 1.30319901 4.69817804 0.13843141 0.74359276 -3.87730702].

split pilot
#

The numbers are wrong.

winged prairie
#

Yes and so how can I do the right caluclations then for the equation

#
A = np.array([[1,2,3],[0,1,0], [0,0,5]])
B = np.array([[1], [2], [4]])
row_echelon_form(A,B)
#
w2_unittest.test_row_echelon_form(row_echelon_form)
spice juniper
winged prairie
#

Do know

#

Was thanking

split pilot
#

I think there is a error in the formula.

winged prairie
#

Yes as I do agreed

#

No idea what it might be

split pilot
#

Well, how does back substitution work?

winged prairie
#

No it does not as got the wrong numbers with the formula as no idea what the main issue could be

split pilot
#

That is because it does the wrong calculations.

winged prairie
#

What should it be then

#

I tried to figure this out

split pilot
#

What is this line of code good for? row_to_reduce = row_to_reduce - value * substitution_row

winged prairie
#

Trying to do

#

A = np.array([[1,2,3],[0,0,0], [0,0,5]])
B = np.array([[1], [2], [4]])
reduced_row_echelon_form(A,B)
array([[1., 2., 3., 1.],
[0., 0., 0., 1.],
[0., 0., 1., 0.]])

#

M[j] = M[j] - value_below_pivot * M[row]

split pilot
#

Hm. But why would you multiply the M[row] with the value? I don't see how that makes sense.

winged prairie
#

What should I use then

split pilot
#

What do your debug prints say?

winged prairie
#

array([[1. , 2. , 3. , 1. ],
[0. , 1. , 0. , 2. ],
[0. , 0. , 1. , 0.8]])

#

All tests passed

split pilot
#

"All tests passed" sounds great.

#

So you fixed it already.

winged prairie
#

I did try put it shows the wrong numbrs

#

array([[1., 2., 3., 1.],
[0., 0., 0., 1.],
[0., 0., 1., 0.]])

#

It should be show thing

split pilot
#

I mean you have this debug print print(f"DEBUG: end result = \n{M}.")
It should show the final matrix after back substitution. And this matrix should consist mainly of zeroes.

winged prairie
#

[ 0. 0. 1. 1.]].
DEBUG: viewing row 1 ([ 0. 1. 0. -2.]) index 1 (1.0).
DEBUG: reducing row 0 ([1. 8. 0. 3.]) index 0 (1.0).
DEBUG: reducing using value = 8.0.
DEBUG: end result =
[[ 1. 0. 0. 19.]
[ 0. 1. 0. -2.]
[ 0. 0. 1. 1.]].
DEBUG: viewing row 0 ([ 1. 0. 0. 19.]) index 0 (1.0).
DEBUG: end result =
[[ 1. 0. 0. 19.]
[ 0. 1. 0. -2.]
[ 0. 0. 1. 1.]].

split pilot
#

Ah, that looks fine.

#

I suppose the function is fine then for the input matrix.

winged prairie
#

Yes as it does

#

Thank you

split pilot
#

So the bug must be elsewhere.

winged prairie
#

Yes

split pilot
#

Or maybe the function works for some test input, but not all test inputs. As the function makes some assumptions.

#

The function assumes that the first non-zero value of each row is a 1.0.

winged prairie
#

What suggestion then

#

!pastebin

rustic lightBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

split pilot
#

The suggestion is to satisfy that assumption.

winged prairie
#

I acually got 100% on that as it now works as back_subtitution is the main issue now

split pilot
#

But it returns a Nx1 matrix instead of a vector. Not sure if that's correct.

winged prairie
#

Okay then how should I fix it then

split pilot
#

Ah, I'm sorry. I read that wrong. It actually returns a vector.

#

So everything works. Great.

winged prairie
#

Yes

#

Thank you again for the help and why spend this long with me

#

.close

#

!close

rustic lightBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.