Matlab |
Python |
description |
## workspace | ||
who |
for vars in dir():   if vars.startswith("__") == 0:   print vars |
In python dir() and locals() are helpful, except you have to get rid of the '__' vars. Dealing with imports is shown here. |
whos | vars() or dir() or dir(object) | get the local vars or attributes of a particular object |
class('1') | type('1') or a.dtype.name | check the type of variable |
## timing | ||
tic; disp(); toc |
import timeit timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) #only for small pieces of code with no imports or from datetime import datetime startTime = datetime.now() dir() print datetime.now() - startTime or time python yourprogram.py | time functions |
## strings | ||
num2str(1) | str(1) | int to str |
num2str(1,'%.2f') |
format(1,'.2f') or '{:.2f}'.format(1) | int to str with 2 digits |
str2num('1') | int('1') | str to int |
? | int('0x01',0) | hex str to int |
double('a') | ord('a') #opposite is chr(97) | char to int |
dec2bin(10) | bin(10) #opposite is 0b1010 | dec to bin |
rats(0.25) | (0.25).as_integer_ratio() | double to fraction |
? | '/'.join(string) | join a list with slashes in btw |
strcmp('abc','b') | a==b | compare strings |
strrep('abc','b','c') | 'abc'.replace('b','c') | replace string |
strcmp(class('abc'),'char') | isinstance('abc',str) | check if something is a string |
## arrays | ||
b = a(a>0) | b = a[a>0] | select positive elements |
b(end+1) = 10; %b must exist | b.append(10) #b must exist | append values to array |
length(a) | len(a) | length of list |
size(a) | s.shape #or a.size for max of mat? | length of matrix |
length(size(a)) | a.ndims | number of dimensions in array |
a=1:10; b=1+0*a; c = [a' b'] | np.hstack( (np.mat(a).T, np.mat(b).T) ) | concatenate arrays |
isnan(a) | np.isnan(a) | find values that are nan in an array |
## figures | ||
clf | plt.clf() | clear figure |
gcf | plt.gcf() | get current figure |
gca | plt.gca() | get current axis |
grid on | plt.grid(True) | turn grid on |
axis('tight') | plt.axis('tight') | tight axis |
xlabel('x') | plt.xlabel('x') | xlabel |
stairs(1:3) | plt.step(range(1,4)) | horizontal lines plot |
clim([x1,x2]) | plt.clim(x1,x2) | color limit |
imagesc(a) colorbar |
plt.imshow(a, aspect='auto', origin='lower') plt.colorbar() | show matrix as an image |
set(gca,'xticklabel',la) | plt.gca().set_xticklabels(la) | replace xticklabels |
## misc | ||
1 ~= 2 | 1 != 2 | check if two things are not equal, note that ~ in python means invert integer's twos-complement representation, so most like you you want 'not' or '!' |
plot.m | execfile('plot.py') | execute script |
a = (0:9).^2 | a = [x**2 for x in range(10)] | list comprehensions |
? | convert -set delay 3 -loop 0 *.png Output.gif | animations |