[ i<=j ? v[j*(j-1)/2+i] : 0 for i=1:n, j=1:n ]
function vec2utri{T}(v::AbstractVector{T}, z::T=zero(T))n = length(v)s = iround((sqrt(8n+1)-1)/2)s*(s+1)/2 == n || error("vec2utri: length of vector is not triangular")[ i<=j ? v[j*(j-1)/2+i] : z for i=1:s, j=1:s ]end
importall Base
type UpperTriDiag{T<:Number} <: AbstractMatrix{T}
data::Vector{T}
size::(Int,Int)
UpperTriDiag(data::Vector{T}) = new( data, _get_uppertridiag_size( data ) )
end
size{T<:Number}(mat::UpperTriDiag{T}) = mat.size
size{T<:Number}(mat::UpperTriDiag{T},i::Int) = i<3 ? mat.size[i] : thorw("Only 2x2 matrix")
function _get_uppertridiag_size(vec::Vector)
len = length(vec)
numerator = sqrt( 8len + 1 ) -1
if numerator % 2 != 0
throw("Not valid vector length")
end
n = div( numerator , 2 )
(n,n)
end
function getindex{T<:Number}(mat::UpperTriDiag{T},i::Int,j::Int)
n=size(mat)[1]
i > j ? zero(T) : mat.data[ i + (n*(j-1)) - ((n-(j-1))*(j-1)) - (0.5 * ( (j-1)*(j-2) ) ) ]
end
ndims{T<:Number}(mat::UpperTriDiag{T}) = 2
julia> UpperTriDiag{Int}([1,2,3])
2x2 Int64 UpperTriDiag:
1 2
0 3
julia> UpperTriDiag{Int}([1,2,3,4])
ERROR: "Not valid vector length"
in _get_uppertridiag_size at none:5
in UpperTriDiag at none:4
julia> UpperTriDiag{Int}([1,2,3,4,5,6])
3x3 Int64 UpperTriDiag:
1 2 4
0 3 5
0 0 6
julia> a = UpperTriDiag{Int}([1,2,3,4,5,6])
3x3 Int64 UpperTriDiag:
1 2 4
0 3 5
0 0 6
julia> a[1,1]
1
julia> a[1,2]
2
julia> a[3,1]
0
julia> dump(a)
UpperTriDiag{Int64}
data: Array(Int64,(6,)) [1, 2, 3, 4, 5, 6]
size: (Int64,Int64) (3,3)
I am not so familiar with handling of symmetric and triangular matrices in Julia. Is there some built-in support for this?
Why not iterate over the 2d matrix with linear indexing?
Hello, I've posted my code at: web.mit.edu/pcaplan/www/codes/SecondDerivOpt.zip, enjoy!Philip
ERROR: ArgumentError: Triangular matrix must have two dimensions
in similar at linalg/triangular.jl:27
in reshape at abstractarray.jl:213
in vec at abstractarraymath.jl:14