How to find same nearby values and sort them
2 次查看(过去 30 天)
显示 更早的评论
Hello, please help sort the task:
(example of data file below)
03/11/2016 2098.8 0
02/11/2016 2109.43 1
01/11/2016 2128.68 0
31/10/2016 2129.78 0
28/10/2016 2132.23 0
27/10/2016 2144.06 1
26/10/2016 2136.97 1
25/10/2016 2149.72 0
24/10/2016 2148.5 1
21/10/2016 2139.43 0
20/10/2016 2142.51 0
19/10/2016 2140.81 0
18/10/2016 2138.31 0
17/10/2016 2132.95 0
14/10/2016 2139.68 1
I need to sort out the data based on the third column. In particular, if we have 2,3,5,8 sets 1s or 0s I need to note the first date, last date, first and last date's numbers of second column, how many subsequent elements were there.
For example, starting from the top, output matrix for the first set will be:
01/11/2016 2128.68 28/10/2016 2132.23 3
P.S. additional question how to sort data file so that the dates would be ascending from top to bottom?
Thank you!
7 个评论
采纳的回答
dpb
2017-2-19
编辑:dpb
2017-2-20
Given x is the third data column of [0 1...]
>> dx=diff(x)==0; % logical vector where difference is 0; ergo x(i+1)==x(i)
>> ix=[[dx;false] [false; dx]]; % arrange so here==next and here==previous in two columns
>> i1=find(ix(:,1) & ~ix(:,2)); % equals next but not previous (begin run)
>> i2=find(ix(:,2) & ~ix(:,1)); % equals previous but not next (end run)
>> [i1 i2 i2-i1+1] % display results -- start,stop,number for each group
ans =
3 5 3
6 7 2
10 14 5
>>
Use i1, i2 to build desired output array as wanted. Can do some combining if care to; kept intermediaries and doubled-up on the test so can see the "how"...
NB: The two logical tests can be written as
>> find(xor(ix(:,1),ix(:,2))).'
ans =
3 5 6 7 10 14
which returns the locations of each group start/stop in order. This may or may not be more convenient; to get the previous rearrange--
>> reshape(ans,2,[]).'
ans =
3 5
6 7
10 14
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!