FactorialTime
FactorialTime

Reputation: 147

Searching a matrix by row and column

Lets say I have the matrix

dataSet = [400,300,200,100,200,300,400;
             1,  2,  3,  4,  5,  6,  7]

This will give me a 2x7 array with the larger numbers on row 1 and the smaller on row 2.

Lets say I am given the number 200 and asked to find what all the numbers below 200 are. The answer is 3 and 5, because they both correspond to 200, but how can I code this into my script?

Upvotes: 1

Views: 46

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112679

Is this what you want?

[t, ~, u] = unique(dataSet(1,:));
result = accumarray(u, dataSet(2,:).', [], @(x) {x.'});
result = [num2cell(t).' result];

In your example, this gives:

>> result
result = 
    [100]    [         4]
    [200]    [1x2 double]
    [300]    [1x2 double]
    [400]    [1x2 double]

with

result{2,2} =
     3     5
result{3,2} =
     2     6

etc

Upvotes: 0

m.s.
m.s.

Reputation: 16334

>> dataSet(2,dataSet(1,:) == 200)

ans =

     3     5

Upvotes: 2

Related Questions