0

Given the following 4x6 matrix A:

A = [
10 11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27
28 29 30 31 32 33
];

and two variables containing the row and column subscripts (r and c, respectively):

r = [
1 1 1
1 1 1
3 3 3
3 3 3
4 4 4
];

c = [
1 3 6
1 2 4
1 2 6
1 4 5
1 5 6
];

I want to create a new 5x3 matrix B that takes each row and column combination from r and c such that:

B = [
10 12 15
10 11 13
22 23 27
22 25 26
28 32 33
]; 

Note that element B(1,1) is derived by using r(1,1) as the row subscript and c(1,1) as the column subscript. Element B(1,2) takes r(1,2) and c(1,2) as the row and column subscripts. And so on...

I can solve this problem using a nested for loop, but the actual application I am working on has very large matrices and this method leads to a significant bottleneck. Are there better (read: quicker) alternatives?

The for loop for reference:

B = NaN(size(r,1),size(c,2));
for row=1:size(r,1)
    for col=1:size(c,2)
        B(row,col) = A(r(row,col),c(row,col));
    end
end

2 Answers 2

4

Yes, you can index 2D matrices with a single index value that is the concatenation of the columns -- like turning your matrix into a vector by column-by-column. For example, you could access A(4,2) simply using A(8).

So, all you need to do is create a new matrix of indices and then access A at those values:

% input data array
A = [10 11 12 13 14 15;
16 17 18 19 20 21;
22 23 24 25 26 27;
28 29 30 31 32 33];

% number of rows
N_rows = size(A,1);

% row indices
r = [1 1 1;
1 1 1;
3 3 3;
3 3 3;
4 4 4];

% column indices
c = [1 3 6;
1 2 4;
1 2 6;
1 4 5;
1 5 6];

% element indices
idx = (c - 1)*N_rows + r;

% new indexed array
B = A(idx);

% display outputs
disp(B)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the sub2ind function to convert subscripts (r,c) to linear indices ('single index value').

If you need the reverse conversion use ind2sub.

1 Comment

This is dedicated way to go, but you should include at least some code, to make that answer upvoteworthy. This way its rather a comment.

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.