2014-02-27 98 views
1

我想將我的C++代碼翻譯成wolfram,以提高我的計算。 C++代碼創建矩陣並填充它wolfram

for(int i = 0; i < N - 1; ++i){ 
     matrix[i][i] += L/3 * uCoef - duCoef/2 - (double)du2Coef/L; 
     matrix[i][i+1] += L/6 * uCoef + duCoef/2 + (double)du2Coef/L; 
     matrix[i+1][i] += L/6 * uCoef - duCoef/2 + (double)du2Coef/L; 
     matrix[i+1][i+1] += L/3 * uCoef + duCoef/2- (double)du2Coef/L; 
    } 

所有這COEF是常數,N - 我的矩陣的大小。

回答

1
In[1]:= n = 4; uCoef = 2; duCoef = 3; du2Coef = 7; L = 11.; 
matrix = Table[0, {n}, {n}]; 
For[i = 1, i < n, ++i, 
    matrix[[i, i]] += L/3*uCoef - duCoef/2 - du2Coef/L; 
    matrix[[i, i+1]] += L/6*uCoef - duCoef/2 - du2Coef/L; 
    matrix[[i+1, i]] += L/6*uCoef + duCoef/2 + du2Coef/L; 
    matrix[[i+1, i+1]] += L/3*uCoef - duCoef/2 + du2Coef/L]; 
matrix 

Out[4]= { 
    {5.19697, 1.5303, 0, 0}, 
    {5.80303, 11.6667, 1.5303, 0}, 
    {0, 5.80303, 11.6667, 1.5303}, 
    {0, 0, 5.80303, 6.4697}} 

每個已經從原來的被暗示是C之間的根本區別++和數學

0

你應該在Mathematica中使用SparseArray這種帶狀排列改變性格:

n = 5; uCoef = 2; duCoef = 3; du2Coef = 7; L = 11.; 
matrix = SparseArray[ 
      {{1, 1} -> L/3*uCoef - duCoef/2 - du2Coef/L, 
      {i_ /; 1 < i < n, i_} -> -duCoef + 2 L uCoef/3 , 
      {n, n} -> (L/3 uCoef - duCoef/2 + du2Coef/L), 
      Band[{1, 2}] -> L/6 uCoef - duCoef/2 - du2Coef/L, 
      Band[{2, 1}] -> L/6 uCoef + duCoef/2 + du2Coef/L}, {n, n}]; 

[email protected] 

enter image description here

即使您堅持使用For循環,也需要將矩陣初始化爲:

matrix = SparseArray[{{_, _} -> 0}, {n, n}];