Programming tips

MatLab

Basic Info

  • MatLab is a procedural language, not an object oriented one.
  • MatLab is an interpreted language, namely commands are interpreted and executed by matlab on the fly.
  • MatLab, though, features many compiled and optimized inner routines, e.g. based on BLAS, LAPACK and similar, in order to speed up the execution time.
  • Variables do not need to be declared, MatLab will understand automatically the data type.
  • Variables in scripts/workspace are global and persist throughout an interactive session (use whos for info and clear to reset all vars!).
  • Every numerical var is automatically put in a double precision float!
  • Every MatLab variable is a matrix, $1\times1$ in case of scalars and $1\times n$ or $n\times1$ in case of arrays.

Allocation

MatLab will automatically resize matrices as needed when you use larger and larger indices in your code. This feature is very convenient but also very time expensive! (see Preallocation in the MatLab Docs)
Sometimes pre-allocating the size of your matrices can speed up significantly your code. You can use the tic and toc commands to evaluate the time that the CPU spent in some segment of your program. E.g. run the following code, once with and once without the second line.
			      
	N = 100000
	f=zeros(1,N);
	tic
	f(1)=1;
	for i=2:N
	   f(i)=f(i-1)+i;
	end
	rt=toc;
	fprintf('f(%d)=%g, time spent in the cycle = %g s',N,f(N),rt); 
			      
			      

Loop Control Statements

  • for
    Example: calculating the first 20 Fibonacci numbers
    				  
    	x = ones(1,20);
    	x(1)=1;
    	x(2)=1;
    	for n = 3:20
     	   x(n) = x(n-1) + x(n-2)
    	end
    				  
    			        
  • while
    Example: find the first $n$ for which $n!$ has at least 100 digits.
    				    
    	  n = 1;
              nFactorial = 1;
    	  while nFactorial < 1e100
    	     n = n + 1;
    	     nFactorial = nFactorial * n;
              end
              disp(n);
                                        
    			          

Conditional Statements

  • if
    Example: define a $3\times3$ antisymmetric matrix equal to one above the diagonal.
    				  
            n=3
    	clear A
    	for i in 1:n
    	   for j in 1:n
    	       if i < j
    	          A(i,j) = -1;
    	       elseif i > j
    	          A(i,j) = 1;
    	       else
    	          A(i,j)=0;
    	       end
    	    end
    	end
    	A
    				  
    			        

Python

Basic Info

  • Python is an object oriented language, not a procedural one.
  • Python is an interpreted language, namely commands are interpreted and executed by matlab on the fly.
  • Python, though, has many add-on packages, such as NumPy, featuring many compiled and optimized routines, e.g. based on BLAS, LAPACK and similar, in order to speed up the execution time.
  • Variables do not need to be declared, Python will understand automatically the data type.
  • Integers are stored in long (32 bits) format if small enough, otherwise 64 bits will be used.
  • Floating points are usually stored as double precision floating points.
  • Unlike in MatLab, arrays need to be allocated in order to use them, e.g. a=[2,8,4].
  • Unlike MatLab, matrices do not exist in Python, to use them it is necessary to explicitly load in python some NumPy library.

Syntax

Unlike MatLab, where the instruction end is used to indicate the conclusion of a loop or a conditional expression, in Python this in indicated through indentation. Note that indenting the code is a very good practice in any programming language, but in Python it is actually enforced: no script will work without proper indentation!

Loop Control Statements

  • for
    Example: calculating the first 20 Fibonacci numbers
    				  
    	x = [0]*20;
    	x[0]=1;
    	x[1]=1;
    	for n in range(2,19):
     	   x[n] = x[n-1] + x[n-2];
    	   print('x[%d] = %d\n' % (n,x[n]));
    				  
    			        
  • while
    Example: find the first $n$ for which $n!$ has at least 100 digits.
    				    
    	  n = 1;
              nFactorial = 1;
    	  while nFactorial < 1e100:
    	     n = n + 1;
    	     nFactorial = nFactorial * n;
              print('%d' % n);
                                        
    			          

Conditional Statements

  • if
    Example: define a $3\times3$ antisymmetric matrix equal to one above the diagonal.
    Note that matrices do not exist in plain Python and so we must import some NunPy library.
    				  
    	from numpy import matrix
    	from numpy import linalg
    	n=3;
    	A = matrix( [[0]*3,[0]*3,[0]*3] )
    	for i in range(0:n):
    	   for j in range(0:n):
    	       if i < j:
    	          A[i,j] = -1;
    	       elif i > j:
    	          A[i,j] = 1;
    	       else:
    	          A[i,j]=0;
    	print A;
    				  
    			        

Octave