use of for loop for time shift

1 回表示 (過去 30 日間)
aa
aa 2020 年 8 月 14 日
回答済み: Arjun 2024 年 9 月 5 日
I have a data set in two coloums, time and number of events. for every time we have to pick teh crossponding value from second coloumn. I did this by for loop at initial stage. Now I want to pick the number of events in two hours with a shift of one hours. For example, 1-2, 2-3,3-4,4-5 hour.
May someone help me here.
Thank you
  2 件のコメント
Sara Boznik
Sara Boznik 2020 年 8 月 14 日
Maybe will be good if you send us the data.
If I correctly understand you, you need only the pick number like 1 2 3 and not 0.5, 1.5 ...
Some idea would be that you use
if rem(num,1)==0
For more I need your task.
Wish you best of luck.
Rafael Hernandez-Walls
Rafael Hernandez-Walls 2020 年 8 月 14 日
If you have this data,
n=10;
x=[1:n]';y=[1:n]';
% shift of one hours
[x(1:n-1) y(2:n)]

サインインしてコメントする。

回答 (1 件)

Arjun
Arjun 2024 年 9 月 5 日
Hi @aa,
As per my understanding, you have a dataset of time vs number of events, and you want to sum up number of events for each two-hour duration.
To achieve this task in MATLAB, you can use a sliding window approach to sum the number of events within each two-hour window, shifting by one hour each time.
We loop through the dataset using a window size of 2, which corresponds to our requirement of considering time frames 1-2, 2-3, 3-4, etc. We have a step size of 1, which means that after scanning the time frame 1-2, the next time frame will be 2-3, and then 3-4. While considering the window 1-2, we sum up all the entries in the number of events column corresponding to the time within the window. We repeat this iteratively for all the time frames.
Kindly refer to the code below to better understand the approach:
% Sample dataset with two columns: [time, number of events]
data = [
1, 5;
2, 3;
3, 6;
4, 2;
5, 8;
6, 7;
7, 4;
8, 5;
9, 9;
10, 1
];
% Initialize an array to store the sum of events in each two-hour window
eventSums = [];
% Define the window size and step size
windowSize = 2;
stepSize = 1;
% Loop through the data array with the specified window and step size
for i = 1:stepSize:(size(data, 1) - windowSize + 1)
% Calculate the sum of events within the current window
windowSum = sum(data(i:i + windowSize - 1, 2));
% Store the result
eventSums = [eventSums, windowSum];
end
% Display the results
disp('Sum of events in each two-hour window:');
disp(eventSums);
I hope it will help!

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by