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

Accessing Matrix row/col ranges produces incorrect results #26588

Closed
crgfn opened this issue May 10, 2024 · 4 comments
Closed

Accessing Matrix row/col ranges produces incorrect results #26588

crgfn opened this issue May 10, 2024 · 4 comments

Comments

@crgfn
Copy link

crgfn commented May 10, 2024

Initialization

from sympy import Matrix, shape
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(M)
Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

pprint(shape(M))
(3, 3)

Accessing ranges produces incorrect results

print(M[0:1,0:1])
Matrix([[1]])

print(M[0:2,0:2])
Matrix([[1, 2], [4, 5]])

print(M[0:3,0:3])
Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(M[0:9,0:9])
Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

@wermos
Copy link
Contributor

wermos commented May 11, 2024

Can you elaborate on which one of these you think is the incorrect result? Also, it would be nice if you use the code font for the code snippets. You can use single backticks (`) for single lines, and triple backticks (```) for multiline snippets.

As far as print(M[0:1,0:1]) and print(M[0:2,0:2]) and print(M[0:3,0:3]) is concerned, this is expected and documented behavior. See this section for a reference.

I agree that the output of print(M[0:9,0:9]) is surprising.

@wermos
Copy link
Contributor

wermos commented May 11, 2024

I did a little investigating, and the behavior is arising from this part of the code:

if isinstance(i, slice):
i = range(self.rows)[i]
elif is_sequence(i):
pass
else:
i = [i]
if isinstance(j, slice):
j = range(self.cols)[j]
elif is_sequence(j):
pass
else:
j = [j]
return self.extract(i, j)

Here, if i and j are slice instances, their max values are being clamped to the size of the matrix.

I'm not sure if this is the intended/desired behavior or not. If it is, then it should definitely be documented somewhere.

@oscarbenjamin
Copy link
Contributor

This is just how slicing in Python works:

In [58]: l = [1,2,3,4]

In [59]: l[:10]
Out[59]: [1, 2, 3, 4]

@sylee957
Copy link
Member

sylee957 commented May 15, 2024

I don't think that we should change this. It is reasonable and robust that matrix should follow how Python slicing just works, and changing that gives further confusion that benefit.

Also, in general programming advice, you should avoid writing code like x[1:100] in favor of x[1:] or x[2:], if you don't know the length of the list.
It is more robust when the shape of the list changes.

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

4 participants