0

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
Mainland
  • 4,110
  • 3
  • 25
  • 56
  • 1
    Does this answer your question? [Linear indexing, logical indexing, and all that](https://stackoverflow.com/questions/32379805/linear-indexing-logical-indexing-and-all-that) – HansHirse Sep 18 '20 at 06:31

1 Answers1

1

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120