Scalar multiplication (Python)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Haskell | Java | Python



c * \overrightarrow{u}
=
c
*
\begin{bmatrix} 
u_1 & u_2 & ... & u_n
\end{bmatrix}
=
\begin{bmatrix} 
c * u_1 & c * u_2 & ... & c * u_n
\end{bmatrix}


c * A_{m,n} 
=
c
*
\begin{bmatrix}
  a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
  a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  a_{m,1} & a_{m,2} & \cdots & a_{m,n}
\end{bmatrix}
=
\begin{bmatrix}
  c * a_{1,1} & c * a_{1,2} & \cdots & c * a_{1,n} \\
  c * a_{2,1} & c * a_{2,2} & \cdots & c * a_{2,n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  c * a_{m,1} & c * a_{m,2} & \cdots & c * a_{m,n}
\end{bmatrix}


Contents

[edit] Scalar multiplication over vectors

[edit] Iteration

<<scale_vector_iteration.py>>=
def vscale(x, vector):
    newVector = []
    for v in vector:
        newVector.append(v * x)
    return newVector

[edit] Iteration - inplace

<<scale_vector_iteration_inplace.py>>=
def vscale(x, vector):
    for i in range(len(vector)):
        vector[i] *= x;
    return vector

[edit] Recursion

<<scale_vector_recursion.py>>=
def vscale(x, vector):
    if vector:
        return [x * vector[0]] + vscale(x, vector[1:])
    else:
        return []

[edit] List Comprehension

<<scale_vector_list_comprehension.py>>=
def vscale(x, vector):
    return [ x * v for v in vector ]

[edit] Higher Order

<<scale_vector_higher_order.py>>=
def vscale(x, vector):
    return map(lambda v: x * v, vector)

[edit] Scalar multiplication over matrices

[edit] Recursion

<<scale_matrix_recursion_with_vscale.py>>=
def mscale(x, matrix):
    if matrix:
        return [vscale(x,matrix[0])] + mscale(x, matrix[1:])
    else:
        return []

[edit] List Comprehension

<<scale_matrix_list_comprehension.py>>=
def mscale(x, matrix):
    return [ [ x * v for v in vs ] for vs in matrix ]
<<scale_matrix_list_comprehension_with_vscale.py>>=
def mscale(x, matrix):
    return [ vscale(x,vs) for vs in matrix ]

[edit] Higher Order

<<scale_matrix_higher_order.py>>=
def mscale(x, matrix):
    return map(lambda vector: map(lambda v: x * v ,vector), matrix)
<<scale_matrix_higher_order_with_vscale.py>>=
def mscale(x, matrix):
    return map(lambda vector: vscale(x, vector), matrix)
Download code
hijacker
hijacker
hijacker
hijacker