How to get the 3rd column in an array using the values ​​of the 1st and 2nd columns as an index in Matlab

I have an array with three columns:

ABC 10 75 20 30 67 50 85 12 30 98 49 70 

I have values ​​A and B, and I want to get the corresponding value of C. For example, if I enter (30.67), it should display 50.
Does Matlab have any trick to get the C value? (my dataset is very large and I need a quick way)

+4
source share
4 answers

Let your input be defined as

 data = [ 10 75 20 30 67 50 85 12 30 98 49 70]; values = [ 30 67]; 

This should be pretty fast:

 index = data(:,1)==values(1) & data(:,2)==values(2); %// logical index to matching rows result = data(index,3); %// third-column value for those rows 

This gives all the values ​​of the third column, which must match if there should be more than one.


If you want to specify several pairs of values ​​at once and get all the matching results:

 index = any(bsxfun(@eq, data(:,1).', values(:,1)), 1) & ... any(bsxfun(@eq, data(:,2).', values(:,2)), 1); result = data(index,3); 

For example, given

 data = [ 10 75 20 30 67 50 85 12 30 98 49 70 30 67 80 ]; values = [ 30 67 98 49]; 

the result will be

 result = 50 70 80 
+2
source

you can use ismember :

 ABC = [10 75 20 30 67 50 85 12 30 98 49 70]; q = [30 67 85 12]; [~, locb] = ismember( q, ABC(:,1:2), 'rows' ); C = ABC(locb,3); 

Result:

 C = 50 30 

Note that the code assumes that all pairs in q can be found in ABC .

+4
source

You can create a sparse matrix. This solution only works if C does not contain zeros and A and B are integers greater than 0

 A = [10 30 85 98]'; B = [75 67 12 49]'; C = [20 50 30 70]'; S = sparse(A,B,C); S(10,75) % returns corresponding C-Value if found, 0 otherwise. 
+1
source

Try accumarray :

 YourMatrix = accumarray([AB],C,[],@mean,true); 

Thus, YourMatrix will be a matrix of size [max(A) max(B)] with the values C at YourMatrix(A(ind),B(ind)) , with ind desired index A and B :

 A = [10 30 85 98]'; B = [75 67 12 49]'; C = [20 50 30 70]'; YourMatrix = accumarray([AB],C,[],@mean,true); ind = 2; YourMatrix(A(ind),B(ind)) ans = 50 

Thus, when there is a repetition in AB , it will return the corresponding value of C if each unique pair AB has the same value of C The true flag allows accumarray to output a sparse matrix rather than a full matrix.

0
source

All Articles