Skip to content

Instantly share code, notes, and snippets.

@marcoaaguiar
Last active May 16, 2021 19:50
Show Gist options
  • Save marcoaaguiar/df4b5199cfbcb880cb6f480a55f61cba to your computer and use it in GitHub Desktop.
Save marcoaaguiar/df4b5199cfbcb880cb6f480a55f61cba to your computer and use it in GitHub Desktop.
m-list: A MATLAB-like Matrix notation for Python, inpired by f-string
"""
File: mlist.py
Author: Marco Aguiar
Github: https://github.com/yourname
MList: A MATLAB-like Matrix notation for Python inpired by f-string
Are you tired of the unergonomic notation for Python?
Are you tired of thinking: "Does the inner list represents a column or a row?"?
If none of the above, but still you want see some Python trickery, this is for you!
How to use?
- use the syntax m[...], to create a numpy.matrix
- Use `,` to split the elements of the row
- Use `:` to split the rows (equivalent to ; in MATLAB)
- There is only one limitation, you can't make column vectors with more than 3 elements.
But you can make a row vector and transpose it!
Example
>>> from m_list import m
...
... a = m[1]
... b = m[1:2]
... c = m[1:
... 2:
... 3]
... d = (m[1,2,3,4,5])
... Q = m[1, 2:
... 3,-4:
... 5, 6]
... H = m[0.1, 0:
... 0, -3.4]
... print(repr(a), repr(b), repr(c), repr(d), repr(Q), repr(H),sep="\n")
matrix([[1]])
matrix([[1],
[2]])
matrix([[1],
[2],
[3]])
matrix([[1, 2, 3, 4, 5]])
matrix([[ 1, 2],
[ 3, -4],
[ 5, 6]])
matrix([[ 0.1, 0. ],
[ 0. , -3.4]])
"""
from typing import Iterable, List, Tuple, Union
import numpy
class m:
def __class_getitem__(
cls, items: Union[slice, Tuple[Union[float, slice], ...]]
) -> numpy.ndarray:
rows: List[List[float]] = [[]]
# eg: m[1:2:3]
if isinstance(items, slice):
cls._handle_slice(rows, items)
if items.step is not None:
rows.append([items.step])
# eg: m[1,2:3,4]
elif isinstance(items, Iterable):
for item in items:
if not isinstance(item, slice):
rows[-1].append(item)
continue
cls._handle_slice(rows, item)
else:
rows[-1].append(items)
return numpy.matrix(rows)
@staticmethod
def _handle_slice(rows: List[List[float]], item: slice):
rows[-1].append(item.start)
rows.append([item.stop])
if __name__ == "__main__":
a = m[1]
b = m[1:2]
c = m[1:2:3]
d = m[1, 2, 3, 4, 5]
Q = m[1, 2:3, -4:5, 6]
H = m[0.1, 0:0, -3.4]
print(repr(a), repr(b), repr(c), repr(d), repr(Q), repr(H), sep="\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment