0

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!

1 Answer 1

1

In Matlab, the colon operator describes a range between the two values n and m of a container.

For example, given a vector x = {4,2,67,2,5,26}, the following expression takes the values 3 through 6 and saves them in the vector y:

y = x(3:6)

resulting in the following values for y:

67   2   5   26

Another use of it is to index all elements of one dimension of a matrix:

x = rand(5,5)
x(:,1) = 1

would fill the first column of the matrix m with the following:

1.0000    0.9649    0.8003    0.9595    0.6787
1.0000    0.1576    0.1419    0.6557    0.7577
1.0000    0.9706    0.4218    0.0357    0.7431
1.0000    0.9572    0.9157    0.8491    0.3922
1.0000    0.4854    0.7922    0.9340    0.6555

Heres a simplified version of your plotting function:

plot(m(1,[1:3 1]),'*', 'Color',[0 0 0])

which plots values 1 to 3 of the first row of x and afterwards the first value (indicated by the space in the square brackets) The output plot looks like this:

plot(m(1,[1:3 1]),'*', 'Color',[0 0 0])

changing the plot to

plot(x(1,[3:4 1]),'*')

(discarding the coloring here for better comparison) would plot the values at index 3 and 4 with the additional value at index 1 like this:

new values in yellow

As for the import in python, you might have to use "range" as described in this post: Python Equivalent of MATLAB's colon operator

I hope this helps, cheers, Simon

Sign up to request clarification or add additional context in comments.

2 Comments

That was super helpful! Thank you for taking the time to explain!
Glad I could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.