Converting Between Matrix Subscripts And Linear Indices (like Ind2sub/sub2ind In Matlab)


Answer :

This is not something I've used before, but according to this handy dandy Matlab to R cheat sheet, you might try something like this, where m is the number of rows in the matrix, r and c are row and column numbers respectively, and ind the linear index:



MATLAB:



[r,c] = ind2sub(size(A), ind)


R:



r = ((ind-1) %% m) + 1
c = floor((ind-1) / m) + 1


MATLAB:



ind = sub2ind(size(A), r, c)


R:



ind = (c-1)*m + r


For higher dimension arrays, there is the arrayInd function.



> abc <- array(dim=c(10,5,5))
> arrayInd(12,dim(abc))
dim1 dim2 dim3
[1,] 2 2 1


You mostly don't need those functions in R. In Matlab you need those because you can't do e.g.




A(i, j) = x




where i,j,x are three vectors of row and column indices and x contains the corresponding values. (see also this question)



In R you can simply:




A[ cbind(i, j) ] <- x




Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable