9

If I want to draw a y=x^2 graph from 0 to 9 in matlab, I can do

a = [0:1:10]
b = a.^2
plot(a,b)

Using python, I can do the same like below

import matplotlib.pyplot as plt
import numpy as np

a=[x for x in xrange(10)]
b=np.square(a)
plt.plot(a,b)
plt.show()

But to the contrary to my belief that python code is simpler, this takes more lines that matlab. (I guess python tries to make things light weight, so we need to import things when we actually need something, hence more lines..) Can I make above python code simpler(I mean shorter)?

EDIT : I know it doesn't matter and meaningless when it comes to processing time but I was just curious how short the code can become.

4
  • 2
    IMO, simple code may not necessarily mean shorter code.... in your case, I wouldn't have been surprised if python code was longer than matlab, matlab is made specifically for this function but not python. Commented Aug 14, 2016 at 6:17
  • The only real reason your code is longer is because you have to import libraries. You only have to do this once for each file where you want to plot. There's not much use in worrying about such lines. Aside from that, your code is one line longer than matlab. (Aside from that, counting lines is not a great way to measure simplicity, especially in trivial examples like this.) Commented Aug 14, 2016 at 6:24
  • yeah, I understand what you mean and totally agree. I added to the question :) Commented Aug 14, 2016 at 6:44
  • This is a reasonable question : point out a more concise approach (than the boilerplate python) and ask if python can do something similar. Commented Sep 9, 2018 at 23:39

1 Answer 1

10

This is a bit simpler

import matplotlib.pyplot as plt

X = range(10)
plt.plot(X, [x*x for x in X])
plt.show()

but remember that Python is a general purpose language, so it's not surprising it requires a bit more than a specific charting/math tool.

The main clutter is importing the libraries that help about chart plotting and numeric computation, as this is implied for matlab (a tool designed around that).

These lines are however needed only once: they're not a factor, but just an additive constant, going to be negligible even in just slightly more serious examples.

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

3 Comments

yeah, I totally understand. I was just curious how short it can get.
Doing the imports in python does not just magically go away: it's always a bit of a tax.
For a scatterplot replace plt.plot( with plt.scatter(

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.