How to select a value in a matrix based on a pair of vectors?
3 views (last 30 days)
Show older comments
Francisco Francisco
on 23 Oct 2019
Commented: Francisco Francisco
on 24 Oct 2019
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...
1 Comment
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?
Accepted Answer
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
3 Comments
Jeremy
on 23 Oct 2019
Edited: Jeremy
on 23 Oct 2019
You would obviously need to modify the 9-girls(i) line if the dimensions of the problem are different. You could use length(girls) in place of the number 9, in this case, I think. Or [m n] = size(C) and then use m+1 in place of 9 (this might be the more correct solution).
More Answers (1)
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.
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!