Tuesday, March 25, 2014

Generating a Random m x n sparse matrix in python with given number of ones

A friend of mine Sheraz needed a small code chunk in python that could generate a random sparse matrix. The requirement was to be able to generate a m by n matrix where most of the entries are 0's and the user mentions the number of 1's required. I am listing down the code that was written by me and later improved by Sheraz for the purpose of preserving it by making it accessible online. The function genmatrix takes 3 arguments en is required number of 1's, s and n correspond to the number of rows and columns of matrix a

from numpy import *
from random import *
from math import *

def genmatrix(en,s, n):
    count=0
    S=range(s)
    N=range(n)   
    a = zeros(shape=(s,n))
    while (count < en):
        i= randint(0,s-1)
        j= randint(0,n-1)
        print i, j
        if (i in S) and (j in N):
            a[(i,j)]=1
            S.remove(i)
            N.remove(j)
            count +=1
    #print a
    #print [sum(a[i]) for i in range(s)]
    #print [sum(a[:,i]) for i in range(n)]
    return a 

Sunday, February 16, 2014

Ubuntu Terminal Commands

Just wanted to keep track of commands and configurations I frequently forget and google.


For unzipping a .zip file via terminal

unzip file.zip -d destination_folder
For copying files using ssh

scp [[user@]from-host:]source-file [[user@]to-host:][destination-file]


from-host: Is the name or IP of the host where the source file is, this can be omitted if the from-host is the host where you are actually issuing the command

user: Is the user who has the right to access the files and directories to be copied in case of from-host, and the user who has the rights to write in case of to-host

source-file: Is the file or files that are going to be copied to the destination host, it can be a directory but in that case you need to specify the -r option to copy the contents of the directory

destination-file: Is the name that the copied file is going to take in the to-host, if none is given all copied files are going to keep its names