Scan each column without for loop in MATLAB

I = [2 1];
A = [7 11
     8 17];

How can I pick the right value in A without for loop? I is a vector of indices for each column in A. That is I(1) is 8 and I(2) = 11.

Answers


Use sub2ind to generate linear indices based on the right row and column coordinates, then use these to index into A. In this case, I chooses the right row and you want to choose only one element for each column from the first up to the last:

ind = sub2ind(size(A), I, 1:numel(I));
out = A(ind);

Example

>> I = [2 1];
>> A = [7 11
        8 17];
>> ind = sub2ind(size(A), I, 1:numel(I));
>> out = A(ind);
>> out

out =

     8    11

Need Your Help

LTE stack protocol development

stack protocols lte

While reading an article on LTE, I came across a term "LTE Stack Protocol Development". Sadly, there was no further explanation on the term and when I looked it up on google, it turned up all job

EC2 instance role gets 'Unknown' error when attempting aws s3 cp KMS encrypted file

security encryption amazon-ec2 amazon-s3

I've got an ASG that assigns an IAM Role to each of the instances that join it. Therefore, each instance has the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables baked-in, which wi...