如何简洁地计算Julia数组中行项目的%差异 [英] How to calculate % difference of row items in Julia array succinctly

查看:63
本文介绍了如何简洁地计算Julia数组中行项目的%差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

C = reshape([1.0, 2.0,1.1, 2.2, 1.2, 2.3],2,3)'

这为我提供了以下3 x 2阵列:

this gives me the following 3 x 2 array:

3×2 Array{Float64,2}:
1.0  2.0
1.1  2.2
1.2  2.3

我想做的是遍历行并获得项目之间的%差异.因此,对于每一行r,请计算(r-th + 1/r-th)-1,然后将新的第一行的结果都返回零. (例如Col1为(1.1/1.0)-1,然后为(1.2/1.1)-1,然后为Col2中的相同模式)

What I want to do is iterate through the rows and get the % difference between items. So for each row r calculate (r-th+1 / r-th) - 1 and then return the results with the new first row all zeros. (ex. Col1 would be (1.1/1.0)-1 then (1.2/1.1)-1 and then the same pattern in Col2)

我正尝试通过以下方式来理解:

I'm trying to do it with the following for comprehension:

[zeros(length(C[1,:]),1);[(C[i+1,:] ./ C[i,:]) - 1 for i=1:length(C[:,1])-1]]

我希望得到的是:

3×1 Array{Float64,2}:
[0.0,0.0]
[0.1,0.1]            
[0.0909091,0.0454545]

但是我得到的是:

4×1 Array{Any,2}:                   
0.0                   
0.0                   
[0.1,0.1]            
[0.0909091,0.0454545]

  1. 如何使我的第一行零匹配(从而使Array的类型正确为Float64)?

...甚至更好...

...or even better...

  1. 是否有一种不太笨拙的方法将N-1行从数组中拉出,然后加零行(是否有更规范的Julia方式)?

推荐答案

Julia的主要优点之一是,在循环清晰明了的情况下,您无需编写矢量化代码:

One of the main advantages of Julia is that you don't need to write vectorized code, when a loop is clear and simple:

C = [1.0 2.0;
     1.1 2.2; 
     1.2 2.3;]

function row_diff(a)
    b = similar(a)
    b[1,:] = 0
    for i in 2:size(a,1)
         b[i,:] = a[i,:] ./ a[i-1,:] - 1
    end
    return b
end

输出:

julia> row_diff(C)
3×2 Array{Float64,2}:
0.0        0.0      
0.1        0.1      
0.0909091  0.0454545

实际上,Julia中的纯循环通常会更快,因为您可以避免中间副本并保持缓存局部性(Julia数组具有列主要顺序):

In fact, pure loops in Julia are often faster, because you can avoid intermediate copies and maintain cache locality (Julia arrays have column major order):

function row_diff_fast(a)
    b = similar(a)
    for j in 1:size(a,2)
        b[1, j] = 0
        for i in 2:size(a,1)
            b[i,j] = a[i,j] / a[i-1,j] - 1
        end
    end
    return b
end

如果您真的想要单线(与上面的直接循环相比要慢):

If you really want a one-liner (which is slow compared to the direct loop above):

[zeros(1,size(C,2));diff(C,1)./C[1:end-1,:]]

这篇关于如何简洁地计算Julia数组中行项目的%差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆