ind2sub用于三角矩阵的非零元素 [英] ind2sub for nonzero elements of triangular matrix
问题描述
我只是想简单地找到(row,col)的索引,它是矩阵A的最小点.我可以使用
I just wanted to simply find the index of (row, col) that is a minimum point of a matrix A. I can use
[minval, imin] = min( A(:) )
和MATLAB内置函数
and MATLAB built in function
[irow, icol] = ind2sub(imin);
但是出于效率的原因,在矩阵A为三角形的情况下,我想实现以下功能
But for efficiency reason, where matrix A is trigonal, i wanted to implement the following function
function [i1, i2] = myind2ind(ii, N);
k = 1;
for i = 1:N
for j = i+1:N
I(k, 1) = i; I(k, 2) = j;
k = k + 1;
end
end
i1 = I(ii, 1);
i2 = I(ii, 2);
此函数在以下输入中返回8和31
this function returns 8 and 31 for the following input
[irow, icol] = myind2ind(212, 31); % irow=8, icol = 31
如何在不使用内部"I"的情况下更有效地实现myind2ind函数?
How can I implement myind2ind function more efficient way without using the internal "I"?
推荐答案
I
矩阵可以由 nchoosek
生成.
例如,如果 N = 5
,我们有:
N =5
I= nchoosek(1:N,2)
ans =
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
这样
4 repeated 1 times
3 repeated 2 times
2 repeated 3 times
1 repeated 4 times
我们可以使用 Gauss公式获得 I
的行数三角数
We can get the number of rows of I
with the Gauss formula for triangular number
(N-1) * (N-1+1) /2 =
N * (N -1) / 2 =
10
给出 jj = size(I,1)+1-ii
作为从 I
的末尾开始的行索引 I
,并使用 N *(N -1)/2
,我们可以得出一个二次方程:
Given jj = size(I,1) + 1 - ii
as a row index I
that begins from the end of I
and using N * (N -1) / 2
we can formulate a quadratic equation:
N * (N -1) / 2 = jj
(N^2 -N)/2 =jj
所以
N^2 -N - 2*jj = 0
它的根是:
r = (1+sqrt(8*jj))/2
可以对
r
进行四舍五入并从 N
中减去以获得所需输出的第一个元素(三角矩阵的行数).
r
can be rounded and subtracted from N
to get the first element (row number of triangular matrix) of the desired output.
R = N + 1 -floor(r);
对于列号,我们找到当前行 R
的第一个元素 idx_first
的索引:
For the column number we find the index of the first element idx_first
of the current row R
:
idx_first=(floor(r+1) .* floor(r)) /2;
可通过从当前行的第一个元素的线性索引中减去当前线性索引并向其添加 R
来找到列号.
The column number can be found by subtracting current linear index from the linear index of the first element of the current row and adding R
to it.
这是已实现的功能:
function [R , C] = myind2ind(ii, N)
jj = N * (N - 1) / 2 + 1 - ii;
r = (1 + sqrt(8 * jj)) / 2;
R = N -floor(r);
idx_first = (floor(r + 1) .* floor(r)) / 2;
C = idx_first-jj + R + 1;
end
这篇关于ind2sub用于三角矩阵的非零元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!