无嵌套循环的迭代矩阵

无嵌套循环的迭代矩阵

本文介绍了无嵌套循环的迭代矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用嵌套循环的情况下,对大小为n的方阵的主对角线上方的条目进行迭代.

I want to iterate the entries above the main diagonal of a square matrix of size n without using nested loops.

例如,如果矩阵M的大小为n = 3,则对角线上方存在choice(3,2)= 3个条目.选择的是二项式系数.

For example if the matrix M is of size n=3, then there are choose(3,2)=3 entries above the diagonal. where choose is the binomial coefficient.

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

我无法提出基于索引i获取行和列的公式.

I have not been able to come up with a formula for getting row and col based on index i.

例如:

对于大小为3且索引从1开始的矩阵

for a matrix of size = 3 and indexes starting at 1,

i = 1对应于row = 1和col = 2

i=1 corresponds to row = 1 and col = 2

i = 2对应于row = 1和col = 3

i=2 corresponds to row = 1 and col = 3

i = 3对应于row = 2和col = 3

i=3 corresponds to row = 2 and col = 3

推荐答案

您可以使用MATLAB的triu命令,如下所示:

You can use triu command of MATLAB as follows:

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)将包含row = 1和col = 4的元素.

u_ind will contain the elements above the upper triangle in the desired format i.e. u_ind(3) will contain the element at row=1 and col=4.

要获取这些行和列索引,可以按以下方式获取它们:

To get these row and column indices, you can get them as follows:

%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);

这篇关于无嵌套循环的迭代矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 02:46