0
votes

In the MATLAB, a matrix cell is numbered by its row and column position. I wanted to index by the integer number.

Consider a (3,4) matrix

for i=1:length(3)
  for j =1:length(4)
    fprint(i,j)
  end
end
1,1
1,2
.
.
3,4

However, the output I am expecting when iterating through each cell is given by

for i=1:length(3)
  for j =1:length(4)
    fprint(i+j+something)
  end
end
1
2
3
4
.
.
12
1
Does this answer your question? Linear indexing, logical indexing, and all thatHansHirse

1 Answers

1
votes

This is called linear indexing. You can use the function sub2ind to convert from row and column number to linear index, and ind2sub to go the other way.

index = sub2ind(size(M),i,j);
M(i,j) == M(index)

The formula applied by sub2ind for a 2D matrix is index = i + (j-1) * size(M,1). That is, numbers increase downward along the first column, then the second column, etc.