Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

matlab

I have an array with three columns like this:

 A       B      C
 10      75     20 
 30      67     50 
 85      12     30
 98      49     70

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

like image 832
mdf Avatar asked Mar 16 '23 00:03

mdf


2 Answers

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);

The result you get is

C =
50
30

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

like image 89
Shai Avatar answered Apr 27 '23 15:04

Shai


Let your input data 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 third-column values that match, should there be more than one.


If you want to specify several pairs of values at once, and obtain all 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 would be

result =
    50
    70
    80
like image 23
Luis Mendo Avatar answered Apr 27 '23 15:04

Luis Mendo