[julia-users] Re: Vector to column matrix

2014-04-29 Thread Matt Bauman
It'd be nice to allow up to one missing dimension in the dimension tuple, 
and calculate it automatically.  Something like this works nicely, where 
the missing dimension is specified by ():

function Base.reshape{N}(a::AbstractArray, dims::NTuple{N,Union(Int,())})
missing_mask = [isa(x,Tuple) for x in dims]
sum(missing_mask) == 1 || throw(DimensionMismatch(new dimensions 
$(dims) may only have up to one omitted dimension))
sz = length(a) / sum(dims[!missing_mask])
sz == int(sz) || throw(DimensionMismatch(array size $(length(a)) must 
be divisible by the product of the new dimensions $(dims[!missing_mask])))
reshape(a,map(x-isa(x,Tuple) ? int(sz) : x, dims))
end

Then: reshape(linspace(0, 10), ((), 1)) would do the trick.


On Tuesday, April 29, 2014 2:07:41 PM UTC-4, Tom Nickson wrote:

 Is there an built-in way to convert a vector to a column matrix without 
 transposing twice?
 I can make a matrix into a vector with vec or squeeze, but I can't see a 
 simple way to convert from a 1d array to a 2d without initialising it, 
 calling reshape and having to measure the size.

 I've put this definition in my .juliarc:

 colmat{T}(x::Array{T, 1}) = reshape(x, (length(x), 1))

 and do colmat(linspace(0, 10)), for example.

 Is there a better way?



[julia-users] Re: Vector to column matrix

2014-04-29 Thread Matt Bauman
Oops:  prod, not sum:

function Base.reshape{N}(a::AbstractArray, dims::NTuple{N,Union(Int,())})
missing_mask = [isa(x,Tuple) for x in dims]
sum(missing_mask) == 1 || throw(DimensionMismatch(new dimensions 
$(dims) may only have up to one omitted dimension))
sz = length(a) / prod(dims[!missing_mask])
sz == int(sz) || throw(DimensionMismatch(array size $(length(a)) must 
be divisible by the product of the new dimensions $(dims[!missing_mask])))
reshape(a,map(x-isa(x,Tuple) ? int(sz) : x, dims))
end



[julia-users] Re: Vector to column matrix

2014-04-29 Thread Matt Bauman
Ah, this was tried once before to get included in Base, and it was turned 
down.  Colon makes much more sense here (and works better, too). 
 https://github.com/JuliaLang/julia/pull/4263

One final iteration (I'll see if we can get this version into Base):

function Base.reshape{N}(a::AbstractArray, dims::NTuple{N, Union(Int, 
Colon)})
missing_mask = [isa(x, Colon) for x in dims]
sum(missing_mask) == 1 || throw(DimensionMismatch(new dimensions 
$(dims) may only have up to one omitted dimension))
sz = length(a) / prod(dims[!missing_mask])
sz == int(sz) || throw(DimensionMismatch(array size $(length(a)) must 
be divisible by the product of the new dimensions $(dims[!missing_mask])))
reshape(a, map(x-isa(x, Colon) ? int(sz) : x, dims))
end