Created
October 26, 2025 05:37
-
-
Save kevyonan/7a7566f1c494217b8dfd92f91927ff40 to your computer and use it in GitHub Desktop.
a matrix script using SymPy to help people practice doing RREF using elementary row operations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Copyright Kevin Yonan MIT license""" | |
| import sympy | |
| sympy.init_printing(use_unicode=True, wrap_lines=True) | |
| ## import ALL single-letter symbols | |
| from sympy.abc import * | |
| def eval_csv(msg, as_tup=False): | |
| kb_str_input = input(msg) | |
| return eval('('+kb_str_input+')') if as_tup else eval('['+kb_str_input+']') | |
| def get_mat(): | |
| rows,prev=[],0 | |
| while True: | |
| r=eval_csv("enter row, empty to stop: ") | |
| curr=len(r) | |
| if curr<=0: | |
| break | |
| elif prev>0 and prev!=curr: | |
| print(f"given row '{prev}' doesn't match prev row's size '{curr}'") | |
| continue | |
| prev=curr | |
| rows.append(r) | |
| print(f"you gave: {r} | curr mat size: {len(r)}") | |
| return sympy.Matrix(rows) | |
| def get_ijk(msg): | |
| a,b,c=0,0,0 | |
| while True: | |
| entry=eval_csv(f"enter {msg}: ", True) | |
| entry_len=len(entry) | |
| if entry_len < 1: | |
| print("need at least one entry, try again") | |
| continue | |
| else: | |
| a = abs(entry[0])-1 | |
| if entry_len>=2: b=entry[1] | |
| if entry_len>=3: c=entry[2] | |
| break | |
| return a,b,c | |
| def run(): | |
| cont=True | |
| msgs=("i & j","i, j, & k","i & k") | |
| while cont: | |
| M=get_mat() | |
| if len(M)<=0: continue | |
| undo_stk=[M.copy()] | |
| while True: | |
| print(""); sympy.pretty_print(M) | |
| try: | |
| op=int(input("Row Ops::\n[1] Swap Rows:: Ri<=>Rj\n[2] Add Row with scaled Row:: Ri = Ri + k * Rj\n[3] Scale Row:: Ri = k * Ri\n[0] Undo Previous Op\n[<0]Quit\nChoose Op: ")) | |
| if op==0: | |
| if len(undo_stk)>1: | |
| M=undo_stk.pop() | |
| elif op<=3 and op>=1: | |
| undo_stk.append(M.copy()) | |
| i,j,k=get_ijk(msgs[abs(op-1)]) | |
| if op<3: | |
| j=abs(j)-1 | |
| if op==1: | |
| ## elementary_row_op(op,row,k,row1,row2) | |
| M = M.elementary_row_op('n<->m',None,None,i,j) | |
| elif op==2: | |
| M = M.elementary_row_op('n->n+km',i,k,None,j) | |
| elif op==3: | |
| M = M.elementary_row_op('n->kn',i,j) | |
| else: | |
| break | |
| except BaseException as err: | |
| print(err); | |
| continue | |
| cont=len(input("restart?: "))>0 | |
| run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment