Project function for Arrays

154 views
Skip to first unread message

Rajath Shashidhara

unread,
Jun 30, 2015, 5:57:00 AM6/30/15
to juli...@googlegroups.com
Hi,

I would like to propose the addition of this function to Julia.
Given a matrix/vector, the function should return the projection along that direction.
for e.g - 
A = [1,2,3,4,5] ; proj(A, 2) = [0,2,0,0,0]
A = 1   2   3   4  5
      6   7   8   9  10
      11 12 13 14 15
proj(A, 4, 2) = 0 0 0 0 0
                     0 0 0 9 0
                     0 0 0 0 0
proj(A, 4) =  0 0 0 4  0
                  0 0 0 9  0
                  0 0 0 14 0


Thank you,
Rajath Shashidhara

Jiahao Chen

unread,
Jun 30, 2015, 9:15:19 AM6/30/15
to juli...@googlegroups.com
You can do almost exactly what you want with this simple function:

julia> function proj(A, i...)
           B = zeros(A)
           B[i...] = A[i...]
           B
       end
proj (generic function with 1 method)

julia> proj(reshape(1:15, 5, 3), 4, 2)
5x3 Array{Int64,2}:
 0  0  0
 0  0  0
 0  0  0
 0  9  0
 0  0  0

What use cases would merit including a function like this in Base? (I don't see any compelling uses of this function.)

Thanks,

Jiahao Chen
Research Scientist
MIT CSAIL

Rajath Shashidhara

unread,
Jun 30, 2015, 9:37:19 AM6/30/15
to juli...@googlegroups.com
I agree that the implementation is quite easy. But, I believe that this function is quite useful in vector and relational algebra.
For example, the function below calculates the finite difference gradient of a given function in n-dimensional space - 

function finitedifferencegradient{T<:FloatingPoint}(operator::Function, point::Array{T,1}, step::Array{T,1})
    dim = length(point)
    grad = zeros(Complex{T}, dim)
    for i=1:dim
        k = zeros(step)
        k[i] = step[i]/2.0
        grad[i] = (operator((point+k)...) - operator((point-k)...))/(step[i])
    end
    grad, norm(grad)
end

It would be nicer to write it this way:
grad = [(operator(point+proj(step,i))-operator(point-proj(step,i)))/step[i] for i=1:length(point)]

It is not really a big thing, but I think it will be useful in certain situations. 

Thank you,
Rajath Shashidhara 

John Myles White

unread,
Jun 30, 2015, 12:05:34 PM6/30/15
to juli...@googlegroups.com
I think a good rule of thumb is that Base is never allowed to grow, only shrink. Obviously unrealistic when applied universally, but it's a good heuristic for answering the question: "what should go in Base?"

 -- John
Reply all
Reply to author
Forward
0 new messages