Julia对矩阵进行预先赋值

   我们知道,对于MATLAB和JULIA 而言,预先赋值可以获得更快的运算速度,特别是MATLAB. 由于JULIA 经常用循还解决相关问题,预先赋值使用的频率相比MATLAB而言大大减小。不过,还是有一些地方,可能用到的,尽量不要使用CAT 操作,效率低下,速度慢得很。这个原则,还仅是对于MATLAB 还是JULIA,基本上都管用。

   和MATLAB不同,MATLAB往往是使用zeros(n,m)的方法对数值进行赋值,但不等对混合类型(有字符串和数值混在一起的)进行赋值。

  一、Julia的赋值:是对Array进行相应的操作而完成。

julia> a =Array(String,1,7) 
1x7 Array{String,2}:
 #undef  #undef  #undef  #undef  #undef  #undef  #undef


julia> b =Array(Float64,1,7)
1x7 Array{Float64,2}:
 0.0  0.0  0.0  0.0  0.0  0.0  0.0


julia> c=Array(Int64,1,7)
1x7 Array{Int64,2}:
 0  0  0  0  0  0  0


julia> h =Array(kbarData,10000) ; # 自定义类型kbarData的赋值,特别补充

有时,自定义类型还是很常见,对这个赋值有相当大的意义!

julia> e=Array(Any,3,7) 
3x7 Array{Any,2}:
 #undef  #undef  #undef  #undef  #undef  #undef  #undef
 #undef  #undef  #undef  #undef  #undef  #undef  #undef
 #undef  #undef  #undef  #undef  #undef  #undef  #undef


julia> f=Array(Int64,3,7)
3x7 Array{Int64,2}:
 0  0  0  0  0  0  0
 0  0  0  0  0  0  0
 0  0  0  0  0  0  0

julia> g=Array(String,3,7)
3x7 Array{String,2}:
 #undef  #undef  #undef  #undef  #undef  #undef  #undef
 #undef  #undef  #undef  #undef  #undef  #undef  #undef
 #undef  #undef  #undef  #undef  #undef  #undef  #undef

julia> c=Array(String,3,7)
3x7 Array{String,2}:
 #undef  #undef  #undef  #undef  #undef  #undef  #undef
 #undef  #undef  #undef  #undef  #undef  #undef  #undef
 #undef  #undef  #undef  #undef  #undef  #undef  #undef

注意:一维Array,就是一个Vector!

julia> g=Array{String,1}
Array{String,1}

julia> g=Array(String,1)
1-element Array{String,1}:
 #undef

julia> g=Array(String,7)
7-element Array{String,1}:
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef

总之,能赋值的就预先赋值,这样可能比push!大大提高效率。

二、 尽可能替代CAT函数

julia> table =["2014-9-17 15:19" 3260.0 700 3360.0 800 3620.0  12;"2014-9-18 15:
19" 3260.0 700 3360.0 800 3620.0  12]
2x7 Array{Any,2}:
 "2014-9-17 15:19"  3260.0  700  3360.0  800  3620.0  12
 "2014-9-18 15:19"  3260.0  700  3360.0  800  3620.0  12

julia> tab =["2014-9-19 15:19" 3260.0 700 3360.0 800 3620.0  12]
1x7 Array{Any,2}:
 "2014-9-17 15:19"  3260.0  700  3360.0  800  3620.0  12

julia> b=vcat(table,tab)

3x7 Array{Any,2}:
 "2014-9-17 15:19"  3260.0  700  3360.0  800  3620.0  12
 "2014-9-18 15:19"  3260.0  700  3360.0  800  3620.0  12
 "2014-9-19 15:19"  3260.0  700  3360.0  800  3620.0  12


julia> @time newtable =vcat(table,table,table);
elapsed time: 0.102088118 seconds (1039984 bytes allocated)

仅管vcat效率比较低,,因为象matlab或julia的矩阵值存储,事实上是按列来排位的,如果是vcat相当于需要精准地insert N个位置。

但是hcat效率还是很高的,因为,hcat操作相当于append在其中一块(比如,最后,最前,或某一列后),在查找定位时,至少开销少了多好,因此hcat要快。

因此,我们尽量避开cat操作。

我个人建议,在这里,可以使用循还,加快运算速度,当然,从功能上看,用cat操作简单省事,但代价是时间。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值