Selecting elements from an array in MATLAB

I know that in MATLAB in case 1D, 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 I would like to select the individual elements according to the set of tuples that I have. So I can 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 an unacceptable amount of memory for large a and / or tuples. Do I need to convert these tuples into linear indexes, or is there a cleaner way to accomplish what I want without taking up so much memory?

+4
source share
3 answers

Converting to linear indexes seems to be a legal way:

 indices = tuples(:, 1) + size(a,1)*(tuples(:,2)-1); selection = a(indices); 

Note that this is also implemented in the Matlab sub2ind built-in solution, as in nate'2's answer:

 a(sub2ind(size(a), tuples(:,1),tuples(:,2))) 

but

 a = rand(50); tuples = [1,1; 1,4; 2,5]; start = tic; for ii = 1:1e4 indices = tuples(:,1) + size(a,1)*(tuples(:,2)-1); end time1 = toc(start); start = tic; for ii = 1:1e4 sub2ind(size(a),tuples(:,1),tuples(:,2)); end time2 = toc(start); round(time2/time1) 

which gives

 ans = 38 

therefore, although sub2ind easier on the eyes, it is also ~ 40 times slower. If you need to perform this operation frequently, select the method above. Otherwise, use sub2ind to improve readability.

+6
source

if x and y are the vectors of xy values ​​of the matrix a, then sub2und should solve your problem:

 a(sub2ind(size(a),x,y)) 

for instance

a = magic (3)

a =

  8 1 6 3 5 7 4 9 2 
 x = [3 1]; y = [1 2]; a(sub2ind(size(a),x,y)) ans = 4 1 
+3
source

you can refer to the position of a 2D matrix with a 1D number, as in:

 a = [3 4 5; 6 7 8; 9 10 11;]; a(1) = 3; a(2) = 6; a(6) = 10; 

So, if you can get positions in such a matrix:

 a([(col1-1)*(rowMax)+row1, (col2-1)*(rowMax)+row2, (col3-1)*(rowMax)+row3]) 

note: rowmax is 3 in this case

will give you a list of items in col1 / row1 col2 / row2 and col3 / row3.

therefore if

 row1 = col1 = 1 row2 = col2 = 2 row3 = col3 = 3 

You'll get:

 [3, 7, 11] 

back.

0
source

Source: https://habr.com/ru/post/1441450/


All Articles