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
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I have question. A simple code is troubling me a lot. Here is my code: for i=1:length(3) for j=1:length(3) n = sub2ind(size(Rld),i,j); fprintf('%i\n',n) end end For unknown reasons , it prints only 1, not 1..9. Any idea what could be wrong here.
@Mainland: length(3) is 1. You want to do for i=1:3.
oho.. i got it now. This is a simple yet big mistake. THanks a ton.
The index is actually set to index = i + (j - 1) * size(M,1)
@JorenV: Thanks for pointing out the typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.