Mayank Jain
Mayank Jain

Reputation: 2564

Access Elements of Array in MATLAB

I am trying to access some elements of an array in matlab. Consider the scenario below :

a = [1 2 3;4 5 6;7 8 9]

b = [1 2;2 1]

I want to access elements with indices (1,2) and (2,1) from a. I tried using a(b) etc. But none of the methods I tried worked.

How can this be done in matlab without using loops?

Also it would be helpful if you could suggest some good books for such basics in matlab.

Upvotes: 1

Views: 2989

Answers (2)

user1860611
user1860611

Reputation: 529

Matlab lets you access a matrix with a linear index that scans through all the columns of the matrix. So in your case (with a 3x3) a(2,1)=a(2) and a(1,2)=a(4). The answer that @HebeleHododo provided takes your row and column index and converts them into a linear index into matrix a. Just remember that if you want to index a different size matrix, you will need a different linear index for it.

Also, there is a lot of information available online to help with learning matlab at http://www.mathworks.com/help/matlab/index.html#language-fundamentals or you can type doc help into the command window

Upvotes: 0

HebeleHododo
HebeleHododo

Reputation: 3640

First, convert your subscripts to indices using sub2ind:

dim1sub = b(:,1);
dim2sub = b(:,2);

ind = sub2ind(size(a), dim1sub, dim2sub)

After you have the indices

a(ind)

will give you:

ans =

     2
     4

See here for more information on matrix indexing.

Upvotes: 1

Related Questions