2014-02-22 73 views
0

我想在不使用嵌套循環的情況下迭代大小爲n的正方形矩陣主對角線上方的條目。沒有嵌套循環的迭代矩陣

例如,如果矩陣M的大小爲n = 3,則在對角線上方有選擇(3,2)= 3個條目。選擇是二項式係數。

for(i=1 to choose(n,2)) 
    row = getRow(i) 
    col = getCol(i) 
    M[row,col] = some value 

我還沒有能夠拿出一個基於索引i獲取行和列的公式。

例如:

爲大小的矩陣= 3並且從1開始索引,

I = 1個對應於行= 1和col = 2

I = 2對應於行= 1和col = 3

I = 3個對應於行= 2和col = 3

+0

爲什麼你想避免嵌套循環? – pkacprzak

+0

@pkacprzak,因爲我想並行執行它,所以它會簡化事情,而且我很好奇 – Enrique

+0

@Enrique看到我的答案。 –

回答

-2

可以嘗試:

n = 3; 

for(int i = 1; i <= n; i++) 
{ 
    for(int j=i+1; j<=n; j++) 
    { 
     row = i; 
     col = j; 
    } 
} 

結果:
1,2-
1,3-
2,3-

+0

這是一個嵌套循環,我想getRow公式和getCol – Enrique

1

可以使用MATLAB的triu命令如下:

n=5; %user input 

mat=magic(n); 
nRows=size(mat,1); 
nCols=size(mat,2); 

%extract the elements above the main diagonal 
u=triu(mat).*(~eye(n)); 
uT=u.'; %transpose to get the indices in the order you mentioned 

%arrange it in a vector 
u_ind=uT(uT~=0); 

u_ind將包含元素在所需格式上方的三角形上方,即u_ind(3)將包含行= 1和1的元素欄= 4。

要獲得這些行和列的索引,你可以讓他們如下:

%You can easily get this if you make simple observations. For a matrix of size 5x5 
%the number of total elements above main diagonal are: (4+3+2+1) 
%i.e. sum of first n-1 elements -> hence the formula below 
totalIndices=0.5*n*(n-1); 

%number of elements per row you get 
indicesPerRow=n-1:-1:1 

%I observed that there is some relation between its index and its (row,col) subscript. 
%If the index is 5 in a 5x5 matrix, then you can imagine that it is the first non-zero 
%element in the second row -> because first row has 4 elements. If the index was 8, 
%similarly, it would have been first non-zero element in the third row in the upper 
%triangular matrix we have formed. This is what I have translated into code below. 

ind1=cumsum(indicesPerRow); 
ind2=ind1; 

%Enter the number whose (row,col) index you want to find. 
myInd=9; 
ind2(ind1<myInd)=[]; 
pos=find(ind1<myInd,1,'last'); 
ind2=ind2(1); 
ind3=rem(ind2,myInd); 
detRow=pos+1; 
detCol=nCols-ind3; 

fprintf('Index %d corresponds to (row,col)=(%d,%d)\n',myInd,detRow,detCol); 
+0

非常感謝。它的工作,我會多等一會兒,看看有人發佈一個更獨立的編程語言的答案(就像公式一樣)。 – Enrique

+0

我會盡快發佈解釋。 –

+0

@恩裏克我添加了一個解釋。希望它使事情更清楚。您也可以將其轉換爲公式。事實上,我將它作爲一個公式進行開發,然後對其進行編碼。 –

0

所以想要一個公式!好 !讓我們去一些簡單的數學:

r首行的條目數是r*(r+1)/2。因此rowrow*(row+1)/2 <= i的最大整數。所以行是方程

row*(row+1)/2 = i 

它重寫的正解的整數部分爲

row^2 + row - 2*i = 0 

這是第二度方程,所以你可以使用平方根解決它。正解是(sqrt(1+8*i) - 1)/2

所以,你必須:在Python

row(i) = floor((sqrt(1+8*i) - 1)/2) 
col(i) = i - row*(row+1)/2 

演示:

def rc(i): 
    r = floor((-1 + sqrt(1+8*i))/2) 
    return (r, i-r*(r+1)/2) 

測試:

print [rc(i) for i in range(20)] 
[(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (3, 3), 
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4)] 

有了正確的顯示

(0, 0), 
(1, 0), (1, 1), 
(2, 0), (2, 1), (2, 2), 
(3, 0), (3, 1), (3, 2), (3, 3), 
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4), 
... 

注意:我開始所有我的指數爲0.如果您想堅持使用通常的編號,您必須將i,r和c加1。