1

I want to know the number of revolution in each period of time. For example, number of revolutions in period 1 is 3, and number of revolution in period 2 is again 3. But it is not necessarily that the number of revolutions in each period will be the same. See the example please:

Example

I tried to used a for loop but it works for one period, is there is any way that you can help me please?

x = 0:33;
y1 = repmat([0 1].',17,1);
y2 = [0; 0; 0; 0; 0; 0; 5; 5; 5; 5; 5; 5; 5; 0; 0; 0; 0; 0; 0; 0;...
    5; 5; 5; 5; 5; 5; 5; 0; 0; 0; 0; 0; 0; 0];

In other words, how can I know the total number of ones from y1 in each period of y2 when y2==5?

find(y1(:,:)==1&y2==5)

1 Answers1

1

Here is one idea for that:

x = 0:33;
y1 = repmat([0 1].',17,1);
y2 = [0; 0; 0; 0; 0; 0; 5; 5; 5; 5; 5; 5; 5; 0; 0; 0; 0; 0; 0; 0;...
    5; 5; 5; 5; 5; 5; 5; 0; 0; 0; 0; 0; 0; 0];

d = diff([y2(1) y2.']); % find all switches between diferent elements
len = 1:numel(y2); % make a list of all indices in y2
idx = [len(d~=0)-1 numel(y2)]; % the index of the end each group
counts = [idx(1) diff(idx)]; % the number of elements in the group
elements = y2(idx); % the type of element (0 or 5)
n_groups = numel(idx); % the no. of groups in the vector

rev = zeros(sum(elements==5),1);
c = 1;
for k = 1:n_groups
    if elements(k)==5
        rev(c) = sum(y1(idx(k)-counts(k)+1:idx(k)));
        c = c+1;
    end
end

The result is:

rev =
     3
     3
EBH
  • 10,350
  • 3
  • 34
  • 59
  • If I want to know the long of the period for each time, how to add it please? (i.e. # of revolutions in period one is 3 and the time is 7 second, # of revolutions in period two is 3 and the time is 7 second) I updated the image to be clear. – Hisham Alghamdi Oct 05 '16 at 16:56
  • Have a closer look the the `counts` variable in the answer, I think it's what you look for. – EBH Oct 05 '16 at 17:17
  • Sorry @EBH , the values of counts are (6 , 7 , 7 , 7 , 7), which is not similar to what I am looking for. Please accept my apologies for any inconvenient :( – Hisham Alghamdi Oct 05 '16 at 17:22
  • I want rev=(3; 3) and time_period=(7; 7) – Hisham Alghamdi Oct 05 '16 at 17:25
  • `counts(elements==5)` is it. – EBH Oct 05 '16 at 17:27