How to do I separate in segments?

Dear all,
I have a certain numerical value (from 0 to 5) for every second from 0 to a time T. I now want to separate 0 to T in segments of 10 minutes each and calculate the % of each value (from 0 to 5) in each segment. I suppose that it is very simple, but I am new to matlab, so how do I do that?
Thank you very much in advance,
Anastasia

 Accepted Answer

Star Strider
Star Strider on 7 Mar 2015
Edited: Star Strider on 7 Mar 2015
I’m not certain how your data are organised, but with my sample data, this works:
T = 60*60*24; % Secconds/Day
t = 0:T-1; % Time Vector
nv = randi([0 5], 1, T); % Data Vector
nv10 = reshape(nv, 600, []); % Create 10-Minute Segments
counts = hist(nv10, 6);
pct = bsxfun(@rdivide, counts, sum(counts))*100;
Data = nv10(:,1:3) % Sample Initial Data
Dist = counts(:,1:3) % Sample Counts
Pcts = pct(:,1:3) % Sample Percents
The last three lines aren’t necessary for the code. They just let you see the first three columns (30 minutes) of the results of the analysis.

5 Comments

Hello, thank you very much for your answer. I found it a bit complicated though. If we separate the two parts of my question: separate the time into segments and calculate the %, can I use other functions for the first part? for instance, I have T=0:t-1 and then when i want to calculate the % for every 600 seconds, could I use a for loop or step function to do that? Thank you in advance, A.
Saying like for every 120 seconds of T (0:120:T or something), calculate %. or for every step=120 from 0 to T, calculate %. I am sorry if it is very simple, its my level.
My pleasure.
I used the reshape function to create the 10-minute segments. It makes segmenting an array much easier than using loops. Note that to use it, the rows of your your numerical value matrix (that I called ‘nv’) have to be an integer multiple of 600 seconds for reshape (or any similar code) to work.
I used bsxfun to calculate the percents for the same reason. It takes the ‘counts’ matrix and expands the ‘sum(counts)’ vector to equal it in size and then do the division. Multiplying it by 100 creates the percents.
You could certainly use loops for all of these operations, but I do not suggest that approach. Loops have their appropriate uses, but my code, using reshape and bsxfun, is much more efficient and much faster.
Look up the documentation on reshape and bsxfun to understand how they work. Experiment with them in your own sample code.
My pleasure!
If my Answer solved your problem, please Accept it.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!