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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.