Nikita Šišikin
Nikita Šišikin

Reputation: 23

Matlab function into python

I am trying to convert this Matlab code into python, but due to no experience with Matlab I just can't figure out the way I can do it. Could someone help? Basically, only the fplot command makes me confusing.

E = 95;
m = 250;
c = 0.900;
t = 0:1:100;
T = E*t/(m*c);
f = @(t)E*t/(m*c);
fplot(f,[0,100]);

Upvotes: 1

Views: 627

Answers (2)

Alexander Korovin
Alexander Korovin

Reputation: 1475

In my opinion, the answer of Exploore X is not so good (you can lose the calculation speed by about 100 times). Try to use numpy for the best MATLAB code translation (because numpy also uses the concept of vectorization).

Thus, you can use something like this, which looks more like your MATLAB code:

import matplotlib.pyplot as plt
import numpy as np

E = 95
m = 250
c = 0.900
t = np.arange(100+1)
T = E*t/(m*c)
# or using anonymous function ( @(t) ... in matlab )
f = lambda t: E*t/(m*c)

plt.plot(t, T)
# or
# plt.plot(t, f(t))
plt.show()

Using a search engine, you can find many articles about Matlab and Python compatibility (in the sense of the concept of vectorization, for example http://mathesaurus.sourceforge.net/matlab-numpy.html).

Upvotes: 3

Davinder Singh
Davinder Singh

Reputation: 2162

First their are few things to note here :

f = @(t)E*t/(m*c);
fplot(f,[0,100]);

@(t) E*t/(m*c) here @(t) is a variable in equation E*t/(m*c) remaining is constants.

fplot(f, [0, 100]) is function plot where t varies from 0 to 100

PYTHON LOGIC :

import matplotlib.pyplot as plt
E = 95
m = 250
c = 0.900
t = list(range(1, 101))
T = [ E*i/(m*c) for i in t]

plt.plot(T)
plt.show()

Upvotes: 1

Related Questions