1

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.

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@EitanT of course, but I don't usually prefer one-liners when answering questions. They make it seem more complicated than it is.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.