MATLAB Answers

How to find values in a range and save them to different arrays, repeatedly

1 view (last 30 days)
Matthieu Sherwood
Matthieu Sherwood on 10 Dec 2019
Commented: Steven Lord on 10 Dec 2019
Hi all,
I am curious to see if there is a better way to what I am attempting below, in as few lines as possible. I have a column vector with the stimulus times ranging from 0 to 120,000 milliseconds. I would like to divide this vector up into 10,000 millisecond tranches, either in a new vector, a field in a structure, etc. So these tranches would be all the values 0-9,999ms, 10,000-20,0000, all the way to 120,000. My current code (shown below) is long and pretty crude and I'm sure there are quicker, more reliable, and more elegant ways to do this.
target_times= randi(120000,1,64) %imagine that this is my array with times, 64 different time values from 0-120000
... %i have to create a bunch of blank arrays, which will be my ten second tranches.
% i cant use zeros because the size of these arrays will vary based on chance. this is ugly and I'd like to get rid of it
%evaluates if the value indexed is within a certain range and writes it to the appropriate file. I would really like to get rid of all these elifs!
for i=1:length(target_times)
if target_times(i)< 10000
elseif (target_times(i) < 20000) && (target_times(i) >= 10000)
elseif (target_times(i) < 30000) && (target_times(i) >= 20000)
elseif (target_times(i) < 120000) && (target_times(i) >= 110000)
So if anyone has a good idea about how to separate all the values based on what 10,000 ms range they fall in, without having to predefine 12 blank arrays and write 12 different elif statements, I would appreciate it!
Steven Lord
Steven Lord on 10 Dec 2019
There may be an even easier way to accomplish your goal than breaking your data set up into smaller pieces, depending on what your goal is. [Some potential tools include retime, groupsummary, grouptransform, etc.] Can you say a little more about what you are planning to do with these tranches?

Sign in to comment.

Accepted Answer

Jeremy on 10 Dec 2019
Edited: Jeremy on 10 Dec 2019
target_times= randi(120000,1,64);
bins = 10000:10000:120000;
c = cell(12,1);
c{1} = target_times(target_times < bins(1));
for i = 2:length(bins)
c{i} = target_times(target_times < bins(i) & target_times >= bins(i-1));
You can access the values in each bin using curly brackets. E.g. c{3}

More Answers (0)

Community Treasure Hunt

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

Start Hunting!