Converting {Array {Float64,1}, 1} to {Float64,2} in Julia

My problem is similar to the previously described problem, with the difference that I do not enter numbers manually. So the accepted answer there doesn't work for me.

I want to convert a vector of Cartesian coordinates to polars:

function cart2pol(x0,
                  x1)
    rho = sqrt(x0^2 + x1^2)
    phi = atan2(x1, x0)
    return [rho, phi]
end

@vectorize_2arg Number cart2pol

function cart2pol(x)
    x1 = view(x,:,1)
    x2 = view(x,:,2)
    return cart2pol(x1, x2)
end



x = rand(5,2)

vcat(cart2pol(x))

      

The last command does not collect arrays for any reason, returning an output of type 5-element Array{Array{Float64,1},1}

. Any idea how to pass it to Array{Float64,2}

?

+3


source to share


2 answers


If you look at the definition cat

(which is the main function for hcat

and vcat

), you can see that you can collect multiple arrays into one dimension 2 array:

cat(2, [1,2], [3,4], [5,6])

2Γ—3 Array{Int64,2}:
 1  3  5
 2  4  6

      

This is basically what you want. The problem is that you have all of your output polar points in the array itself. cat

expects you to supply them as multiple arguments. Here ...

comes in.

...

is used to split one function argument into different arguments when used in the context of a function call.



Therefore you can write

cat(2, [[1,2], [3,4], [5,6]]...)

2Γ—3 Array{Int64,2}:
 1  3  5
 2  4  6

      

In your situation, it works exactly the same (I changed yours x

to have dots in the columns):

x=rand(2,5)
cat(2, cart2pol.(view(x,1,:),view(x,2,:))...)

2Γ—5 Array{Float64,2}:
 0.587301  0.622    0.928159  0.579749  0.227605
 1.30672   1.52956  0.352177  0.710973  0.909746

      

+6


source


The function mapslices

can also do this by essentially converting the input strings:

julia> x = rand(5,2)
5Γ—2 Array{Float64,2}:
 0.458583   0.205246 
 0.285189   0.992547 
 0.947025   0.0853141
 0.79599    0.67265  
 0.0273176  0.381066 

julia> mapslices(row->cart2pol(row[1],row[2]), x, [2])
5Γ—2 Array{Float64,2}:
 0.502419  0.420827 
 1.03271   1.291    
 0.95086   0.0898439
 1.04214   0.701612 
 0.382044  1.49923  

      



The last argument defines the dimensions to work with; for example transfer [1]

will convert columns.

As an aside, I would recommend a stylistic change or two. First, it's good to render as we like, so if we're sticking to string representation then cart2pol

should accept an array of two elements (since it's returned). Then this challenge will only be mapslices(cart2pol, x, [2])

. Or if we are really trying to represent an array of arrays of coordinates, then the data can be an array of tuples [(x1,y1), (x2,y2), ...]

, or it cart2pol

can take and return a tuple. In any case cart2pol

, there would be no need to work with arrays, and partly because of this we have deprecated macros @vectorize_

.

+4


source







All Articles