max value every n interval
7 次查看(过去 30 天)
显示 更早的评论
In this problem, I have a set of data collected every 2sec. This data set divided into several subset that contain 4 data's in each interval.Next, I am interested to find the maximum value in each intervals and the particular time related to that particular max value. For example, in the data set as shown in the figure attached together, I know the maximum value and time associated for each interval was [ 3,6,6,10,23,7] and [ 7,15,23,25,37,41] respectively.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/158631/image.png)
Following this, the syntax below was developed and successfully did what it was intended.
However, this syntax look messy,lengthy and seem not computationally efficient. May I know if there are other faster and compact approach replacing the proposed syntax.
%%%%% This was syntax to solve the above problem.
n=4;
s.Data_to_find = [1 2 1 3 2 4 5 6 2 3 5 6 10 3 4 2 4 5 23 6 7];
s.time = 1:2:42;
%% Ensure empty space fill with something
z_data_to_find = nan (mod (-numel(s.Data_to_find),n),1);
z_time = nan (mod (-numel(s.time),n),1);
%% New matrix will nan fill empty space
a_Data_to_find = [s.Data_to_find(:);z_data_to_find];
a_time = [s.time(:);z_time];
%% Reshape the matrix so that the time and data go from left to right for every interval
b_Data_to_find =(reshape(a_Data_to_find,n,[]))';
b_time =(reshape(a_time,n,[]))';
%% Find the maximum value at each interval and output the column coordinate for each M row
[max_each_row_b_Data_to_find,column_cordinate] = max (b_Data_to_find,[],2);
%%%% This for loop to get the full coordinate of the maximum data value in each of the interval
for i =1:6
idx = column_cordinate (i,:);
location (i,:) = [i idx]
end
%% Accessing the time
for i = 1:6
zzz = location (i,:)
actualtime(i,:) = b_time ((zzz (1,1)),(zzz (1,2)))
end
%% The result
actualtime =
7
15
23
25
37
41
0 个评论
采纳的回答
dpb
2016-12-4
Got the right idea, just can be a little more parsimonious in the implementation...
>> [mx,ix]=max(reshape([Data nan(1,mod(-length(Data),n))],n,[]))
mx =
3 6 6 10 23 7
>> t=reshape([t nan(1,mod(-length(Data),n))],n,[]); % same "trick" for the time vector
>> tmx=zeros(1,length(mx)); % preallocate
>> for i=1:length(ix),tmx=t(ix(i),i);end
>> tmx
tmx =
7 15 23 25 37 41
>>
I'm sure you could use cumprod and accumarray with an offset of n-ix by column and do a direct lookup/accumulation of the time but the loop is "deadahead" and with preallocation will probably be faster anyways...
PS: I like your thinking of using the negative sign with mod to get the right number directly...good job! :)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!