# Get the position of the next in row and next in column in a matrix

6 views (last 30 days)
kalana agampodi on 8 Oct 2021
Commented: De Silva on 15 Oct 2021  I want to get the next in row and next in column in the above matrix.
Index column represent the all non zero entries in the matrix.
For an example if you are at A(1,1) it shoud give me the index for -2 from the index colum and update next in row to 2. Because -2 is index 2 in the index column. For next in colum at A(1,1) it should get the index from index column for 2 so the next in column will be 3.
When you are at A(2,1). The next in row is 8. this should give me 4 from index column (because 8 is the 4th non zero entry in the matrix), for next in column it should give me 10 from index colum because 1 is the 10th non zero entry of the matrix.
De Silva on 12 Oct 2021
yes you are correct @Stephen for index 9, next in row =0 and ,next in column = 0;
Thank you

Stephen23 on 12 Oct 2021
Edited: Stephen23 on 12 Oct 2021
A reasonably simple, efficient, robust approach:
A = [1,0,-2,0,0;2,8,0,1,0;0,0,3,0,-2;0,-3,2,0,0;1,2,0,0,-4]
A = 5×5
1 0 -2 0 0 2 8 0 1 0 0 0 3 0 -2 0 -3 2 0 0 1 2 0 0 -4
[C,R] = find(A.');
N = numel(R);
M = repmat([R,C],1,3);
M(:,1) = 1:N;
M(:,2) = nonzeros(A.');
M(:,5:6) = 0;
for k = 1:N
X = find(C>C(k) & R==R(k),1);
Y = find(R>R(k) & C==C(k),1);
if numel(X)
M(k,5) = M(X,1);
end
if numel(Y)
M(k,6) = M(Y,1);
end
end
disp(M)
1 1 1 1 2 3 2 -2 1 3 0 6 3 2 2 1 4 10 4 8 2 2 5 8 5 1 2 4 0 0 6 3 3 3 7 9 7 -2 3 5 0 12 8 -3 4 2 9 11 9 2 4 3 0 0 10 1 5 1 11 0 11 2 5 2 12 0 12 -4 5 5 0 0
De Silva on 15 Oct 2021
Thank you so much!!!

David Hill on 9 Oct 2021
matlab indexing is down and then across.
A=[1 0 -2 0 0;2 8 0 1 0;0 0 3 0 -2;0 -3 2 0 0;1 2 0 0 -4];
a(a~=0)%shows your indexing for each non-zero in A
Recommend using linear indexing if you can.
%if you are at a(1), then the next row/column (will be reverse yours)
N=1;%current location
[m,n]=size(a);
if mod(N,m)~=0
b=ceil((N+1)/m);
f=find(a(N+1:b*m),1);
if ~isempty(f)
r=mod(N,m)+f;
else
r=[];
end
else
r=[];
end
if N<=m*(n-1)
f=find(a(N+m:m:m*n),1);
if ~isempty(f)
c=ceil(N/m)+f;
else
c=[];
end
else
c=[];
end
David Hill on 12 Oct 2021
I am using linear indexing. A(1,1)==A(1).
a=[1 0 -2 0 0;2 8 0 1 0;0 0 3 0 -2;0 -3 2 0 0;1 2 0 0 -4];
N=1;%current location, linear indexing into A
[m,n]=size(a);
if mod(N,m)~=0
b=ceil((N+1)/m)
f=find(a(N+1:b*m),1)
if ~isempty(f)
nextRowNumber=mod(N,m)+f
else
nextRowNumber=[]
end
else
nextRowNumber=[]
end
if N<=m*(n-1)
f=find(a(N+m:m:m*n),1)
if ~isempty(f)
nextColumnNumber=ceil(N/m)+f
else
nextColumnNumber=[]
end
else
nextColumnNumber=[]
end
Output for A(1), nextColumnNumber=3, nextRowNumber=2
Output for A(7). nextColumnNumber=4, nextRowNumber=4
If you don't like linear indexing you can convert from sub2ind()
sub2ind(size(a),2,2);%which equals 7
I don't plan on responding again.