Syntax error when plotting in Matplotlib

7 views (last 30 days)
Aisse Torres Torres
Aisse Torres Torres on 1 Aug 2018
Answered: Riya on 5 Aug 2025
I am working on translating some code from Matlab into Python. I am a little bit confused in terms of understanding this Matlab code:
plot(m_true(1,[1:p 1]), m_true(2,[1:p 1]),'*', 'Color',[0 0 0])
When I try to translate that into Python it looks something like this:
plot(m_true[1,(1:p, 1)], m_true[2,(1:p 1)],'*', 'Color',[0, 0, 0])
The colon causes a syntax error. Can anyone who has plotting experience in Matlab (I am new to this language) explain the matlab syntax (in terms of what the indexing of 1:p is doing) and perhaps how to fix the syntax error? Thanks!

Answers (1)

Riya
Riya on 5 Aug 2025
Hi Aisse,
I understand that you are trying to translate a MATLAB plotting command into Python and are encountering a syntax error, specifically due to the use of "1:p" in your indexing. This is a common confusion when moving between MATLAB and Python, especially related to indexing conventions and array slicing.
In the MATLAB command:
plot(m_true(1,[1:p 1]), m_true(2,[1:p 1]), '*', 'Color', [0 0 0])
  • “1:p” generates a row vector from 1 to p.
  • “[1:p 1]” appends the first index again at the end, creating a loop back to the starting point — this is a typical approach for plotting closed shapes.
  • “m_true(1, [1:p 1])” accesses the x-coordinates and “m_true(2, [1:p 1])” accesses the y-coordinates from the matrix m_true.
The error in your Python version arises due to the incorrect syntax “1:p”, which is not valid in Python. Python uses 0-based indexing and requires range(start, stop) or list-based indexing.
To resolve the issue and get the equivalent behavior in Python, you can use the following corrected code:
import numpy as np
import matplotlib.pyplot as plt
# Assuming m_true is a NumPy array of shape (2, p)
p = m_true.shape[1]
indices = list(range(p)) + [0] # Creates [0, 1, ..., p-1, 0]
x = m_true[0, indices] # x-coordinates
y = m_true[1, indices] # y-coordinates
plt.plot(x, y, '*', color=(0, 0, 0)) # RGB black
plt.show()
This modification ensures the indexing is compatible with NumPy's syntax and that the final plot mirrors MATLAB's behavior. It also ensures the polygon is closed by looping back to the first point.
For further reference on Python indexing and plotting, you may refer to the following documentation:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!