Search code examples
juliamatrix-multiplication

Why my function works for matrix but why not for vector?


I am confused in the term "Duck-Typing". I've Written a function which is applicable for a matrix but why it gets error whenever I tried to use a vector as parameter?

Here's My piece of code that i've written


Solution

  • In this case it looks like you are lucking out and there happens to be an implementation of the base exponentiation method (^) that is specifically designed for matrices. Probably because matrix powers is commonly useful and I'm willing to bet there are a lot of optimizations for them.

    @which v1^2
    

    ^(A::AbstractArray{T,2} where T, p::Integer) in LinearAlgebra at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\LinearAlgebra\src\dense.jl:366

    But there isn't a built-in for vectors. Note that for matrix A, A^2 means A * A using matrix multiplication rules, not the same as squaring each element in A. For a 2 by 2 matrix A = [a b; c d], you would get:

    A = [a  b]
        [c  d]
    A^2 = [a*a+b*c  a*b+b*d]
          [c*a+d*c  c*b+d*d]
    

    For a vector v, the equivalent I guess would be v^2 = v' * v, the dot product between the transpose of v and v itself, giving you a scalar (now I'm really wishing I could use LaTeX symbols in SO).

    In general, if you want an operator to broadcast (be applied to every element of an array or matrix magically), add a dot in front of it.

    func = v -> println(v.^2)
    func(v2)
    # [0.0826262, 0.127083, 0.513595]
    

    This takes each element of v2 = [a, b, c] and squares it: [a^2, b^2, c^2]. It similarly squares each element of v1 instead of doing the matrix multiplication.