# How to select a value in a matrix based on a pair of vectors?

3 views (last 30 days)
For Example:
We have vectors:
girls boys
2 6
7 5
5 4
4 3
3 3
6 2
8 1
1 6
2 6
And a matrix C:
8 42 37 33 29 25
7 45 39 33 29 25
6 48 40 33 28 24
girls 5 50 40 33 27 24
4 49 38 31 26 22
3 43 34 27 23 19
2 32 25 20 16 13
1 15 11 8 6 5
1 2 3 4 5 6
boys
I would like to make a vector D where I take the value of the matrix C wich is referent to the pair of vectors girls and boys. For example:
girls boys vector D
2 6 48
7 5 29
5 4 33
4 3 38
3 3 34
ect...
Jos (10584) on 23 Oct 2019
I think you made a mistake. How is the value in the third column of D related to other values. I would have expected that for 2 girls and 6 boys, the element 13 would have been picked,rather then 48 ...
Also, why are there only 5 values for each number of girls in C, when there are upto 6 boys?
C cannot be a proper matrix btw. Is it a table with column and row names?

Jeremy on 23 Oct 2019
Edited: Jeremy on 23 Oct 2019
The easiest way I thought of was to use a loop. It's made awkward by the fact that your index for girls is the opposite of the default index matlab uses (i.e. 1,1 being the top-left matrix entry)
%% Vector Manipulation
girls = [2 7 5 4 3 6 8 1 2];
boys = [6 5 4 3 3 2 1 6 6];
%
C = [ 0 42 37 33 29 25;
0 45 39 33 29 25;
0 48 40 33 28 24;
0 50 40 33 27 24;
0 49 38 31 26 22;
0 43 34 27 23 19;
0 32 25 20 16 13;
0 15 11 8 6 5];
%
D = zeros(size(girls));
for i = 1:length(girls)
k = 9-girls(i);
D(i) = C(k,boys(i));
end
Francisco Francisco on 24 Oct 2019
Offscorse I tried "length(girls)" and redimensioned the problem. But this is the error appears: "Index in position 1 is invalid. Array indices must be positive integers or logical values".
I am dealing with real numbers. Is that the problem?

Steven Lord on 23 Oct 2019
If you don't want to use a loop like Jeremy Marcyoniak suggested, you could convert your subscripts into linear indices using sub2ind. As Jeremy pointed out, your data is arranged with the row indices in the reverse order of how the row indices increase in MATLAB, so you would need to either flip / flipud your data or reverse the polarity of your row indices. That's the k = 9 - girls(i); line in Jeremy's code. With the vectorized sub2ind version it would be k = 9-girls; or k = size(C, 1) + 1 - girls; to account for the number of girls not being fixed.
Francisco Francisco on 23 Oct 2019
Thanks for the this effort. It answers part of the issue! However, those were a dummy data, and wneh I apply to my real data it doesn not work!
I would like that matlab to go to matrix C and picks the right combination values based on the pair A and B.
Please have a look at the attached excell file. I would like to fill the yellow column!