How can I create a matrix based on a double vector lookup?

I have three vectors of same length:
a=[5;10;10;15;15;15;20;20;20]
b=[3;3;5;3;5;10;3;5;10]
c=[0.2;0.3;-0.1;0.4;0.5;0.6;-0.2;-0.3;0.7]
The entries in a, b and c are related to each other (e.g. first row a=5, b=3 --> c=0.2).
I would like to translate this into a matrix with unique(a) being the row lookup value, unique(b) the column lookup value and "c" the values resulting from the row and column lookup. Making "a" and "b" unique is not a problem but putting this into a matrix with cross-values of "c" seems to be difficult. For all combinations where there is no match, the value should be zero (=0). Final matrix should look like:
[0, 3, 5, 10; ...
5, 0.2, 0, 0;...
10, 0.3, -0.1, 0;...
15, 0.4, 0.5, 0.6;...
20, -0.2, -0.3, 0.7]
Note: The matrix doen't need to have the some row and column dimension. First row and column are the unqiue lookup values from vector "a" and "b"; vector "c" values are in the matrix (2:end,2:end).

2 Comments

I do not understand the relation between the inputs and outputs exactly.
Think of "a" and "b" as an integer that defines a specific combination and "c" is the cumulated return of this combination. So maybe it helps to visualize if you put the three vectors into a matrix like this:
x=[a,b,c]
x =
5.0000 3.0000 0.2000
10.0000 3.0000 0.3000
10.0000 5.0000 -0.1000
15.0000 3.0000 0.4000
15.0000 5.0000 0.5000
15.0000 10.0000 0.6000
20.0000 3.0000 -0.2000
20.0000 5.0000 -0.3000
20.0000 10.0000 0.7000
Meaning that the combination 5~3 leads to a total return of 20% (row 1) the combination 10~3 results in a total return of 30% and so on...
Now, I aim to make "a" and "b" unique and creating a new matrix looking up the total returns in "c" corresponding the values in "a" and "b".
If you check the result matrix:
result =
0 3.0000 5.0000 10.0000
5.0000 0.2000 0 0
10.0000 0.3000 -0.1000 0
15.0000 0.4000 0.5000 0.6000
20.0000 -0.2000 -0.3000 0.7000
You will find combination 5~3 in result(2,2), combination 10~3 in result(3,2) and so on.

Sign in to comment.

 Accepted Answer

You probably want something like:
[un_a,~,ic_a] = unique(a) ;
[un_b,~,ic_b] = unique(b) ;
result = zeros(length(un_a), length(un_b)) ;
result(sub2ind(size(result), ic_a, ic_b)) = c ;
and if you want to add unique values as row/col 1, you can do it as
result = [0, un_b.'; un_a, result] ;
There are plenty of variants of this solution; what you probably missed when you tried to develop a solution, is that UNIQUE outputs three vectors, the last two being indices that you can use for lookup operations.

More Answers (0)

Categories

Products

Asked:

on 22 Jul 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!