Extract values from rows satisfying a given criteria

52 Views Asked by At

I would like to calculate total income in a shop every 30 minutes,

I have a dataset like:

hour  minute   price

0      1        12,5
0      1        10
0      2        15
0      3        15

I have tried to implement the totalling like this:

[rows,cols,vals] = find(0 < data(:,2) &  data(:,2) < 31 );

but cannot get what I wanted.

2

There are 2 best solutions below

2
m7913d On

You should use logical indexing to obtain the prices in a 30 minute range:

data(0 < data(:,2) &  data(:,2) < 31, 3)

Why find doesn't do what you expect?

find works on the result of the following expression 0 < data(:,2) & data(:,2) < 31, i.e. [1 1 1 1].' It doesn't know anything about the original matrix data. Therefore, the second and third argument are useless in this case. They would be useful to obtain the nonzero elements in a matrix.

As a (less efficient) alternative to logical indexing, you can obtain the same result as follows:

data(find(0 < data(:,2) &  data(:,2) < 31 ), 3)

Selecting a specific hour

At the moment, you select the prices for the first half of each hour. To select for example the prices between 00:00 and 00:30, you could use the following:

data(data(:,1) == 0 && 0 < data(:,2) &  data(:,2) < 31, 3)
0
ömer çel On

I found the solution

data(:,2) =((data(:,2) ./ 30) + 1);
data(:,2)= floor(data(:,2));
changes = find(diff(data(:,2)))+1;

for i=1:1:(length(changes) -1)
A(i)=sum(data(changes(i):changes(i+1),3))
end