2013-05-13 37 views
2

我想創建一個函數,在保持其「形狀」的同時改變整數數組的大小。Java中的數組修改(改變數組「分辨率」)

目的是加快FFT的計算。

它返回一個大小爲y的新數組,其中每個元素是它將「覆蓋」在舊數組中的元素的平均值。例如,如果我有一個帶有3個元素的數組w,並且想要創建帶有2個元素的另一個數組z,則第一個元素是:z[0] = (1 * w[0] + 0.5 * w[1]) * 2/3,第二個元素是:z[1] = (0.5 * w[1] + 1 * w[2]) * 2/3。這有點像改變陣列的「分辨率」。 (當然,數字很小,四捨五入就有可能丟失信息,但我需要它用於幾個數字無關緊要的相當大的數字。)

感覺這是一個非常簡單的問題,但我花了太多時間在靜脈。我確實有一些代碼,儘管我幾乎工作,但我認爲我走錯了路(太多線)。基本上,它循環遍歷原始數組,並計算如何分解每個元素,並跟蹤在哪裏放置一個局部變量。

此外,我的搜索都出現了像動態改變數組大小等等,這不是我想要的。

所以,這裏有一個可能的骨架:

public int[] the_function (int[] w, int y) { 
    int[] z = new int[y]; 

    // Some code looping through the array 

    return z; 
} 
+0

你想通過插值使數組變大,對嗎?如果'y 2013-05-13 14:57:24

+1

我們需要更多關於您正在實施的「想法」的數據。在舊數組中,「覆蓋」是什麼意思?根據什麼規則,你決定'z [0] =(1 * w [0] + 0.5 * w [1])...''但'z [1] =(0.5 * w [1] + 1 * w [ 2])...'?爲什麼'w [1]'在它之前總是有'0.5 *'? – Pshemo 2013-05-13 15:01:53

+0

請發佈您嘗試過的。 – 2013-05-13 15:06:58

回答

1

所以,你想一個過濾器應用於陣列?這是一個天真的實現... 我認爲關鍵在於如何對過濾器進行編碼......我將通過將其表示爲一系列浮點數來代表我想要應用於原始值的百分比產值。這是過濾器的標準。

public static int[] applyFilter(int[] from , float[] filter) { 
    if (filter.length > from.lenth){ 
     throw new IllegalArgumentException("Filter to large to apply to array!"); 
    } 

    int [] to = new int[from.length + 1 - filter.length]; 

    for (int i = 0; i < from.length + 1 - filter.length; i++) { 
     float newValue = 0.0f; 

     for(int j = 0; j < filter.length; j++){ 
      newValue += filter[j] * from[i+j]; 
     } 

     to[i] = Math.round(newValue); 
    } 
    return to; 

} 

而像您的問題指定來調用濾波器,....

public static void main (String ... args){ 
    float[] filter = new float[] { 0.66f, 0.66f }; 
    int[] from = new int[] { 1, 2, 3, 4, 5, 6}; 

    int[] to = applyFilter(from, filter); 
    for (int i : to){ 
     System.out.println(i); 
    } 
} 

處理的從[1]由1/2比例的情況下,可以通過預處理來hadled數組然後再應用過濾器。像這樣:

public static void main (String ... args){ 
    float[] filter = new float[] { 0.66f, 0.66f }; 
    int[] from = new int[] { 1, 2, 3, 4, 5, 6}; 

      // Preprocess to apply static scalars to the source array. 
      int[] frompp = from.clone(); 
      frompp[1] = Math.round((float) from[i]/0.5f); 

    int[] to = applyFilter(from, filterpp); 
    for (int i : to){ 
     System.out.println(i); 
    } 
} 
0

可以使用LCM,最小公倍數,使用積分算術。 您將圖像源數組(w)和目標數組映射/縮放到最小公倍數的網格上。

public static int gcd(int a, int b) { 
    while (a != b) { 
     if (a > b) a -= b; else b -= a; 
    } 
    return a; 
} 

public static int lcm(int a, int b) { 
    return a * (b/gcd(a, b); 
} 

One then can achieve a high precision in averaging. 
For image scaling ideal and fast. 
For your purpose `double` math will do, I think, and saves a bit on index juggling.