I know that in MATLAB, in the 1D case, you can select elements with indexing such as a([1 5 3]), to return the 1st, 5th, and 3rd elements of a. I have a 2D array, and would like to select out individual elements according to a set of tuples I have. So I may want to get a(1,3), a(1,4), a(2,5) and so on. Currently the best I have is diag(a(tuples(:,1), tuples(:,2)), but this requires a prohibitive amount of memory for larger a and/or tuples. Do I have to convert these tuples into linear indices, or is there a cleaner way of accomplishing what I want without taking so much memory?
I know that in MATLAB, in the 1D case, you can select elements with
Share
Converting to linear indices seems like a legitimate way to go:
Note that this is also implement in the Matlab built-in solution
sub2ind, as in nate’2 answer:however,
which gives
so although
sub2indis easier on the eyes, it’s also ~40 times slower. If you have to do this operation often, choose the method above. Otherwise, usesub2indto improve readability.