MATLAB Answers

Need a fast way to create a counter variable

16 views (last 30 days)
Darin McCoy
Darin McCoy on 15 Feb 2013
I'm trying to find a faster way to calculate the time a time series data set is at a particular value. Here is my code (but i KNOW theres gotta be a better way to do this? using diff maybe?) Any ideas on how to make this faster? I need help in the middle section (not the initialization or the plotting)
%Create a sample set of data
time = 0:.12:(.12*10000 - .12);
data = zeros(10000,1);
data(2:100,1) = 1;
data(400:500,1) = 1;
value = 0;
timestep = 0.12;
%%This part will look at time series data and create a variable showing how long the variable has been active
%Initialize
currently_counting = 0;
counter_channel = zeros(size(data));
data_meets_conditions = find(data==value);
%For all of the data
for i = 1:size(data_meets_conditions,1)
%Current index of the data channel that you are going through...
cur_data_index = data_meets_conditions(i);
if currently_counting == 1;
%Use the last counter channel and add a time value to it.
counter_channel(cur_data_index) = counter_channel(cur_data_index-1) + timestep;
end
%Used for the very first case
min_index = max(1,cur_data_index-1);
if data(cur_data_index) == data(min_index)
%Start counting
currently_counting = 1;
else
currently_counting = 0;
end
end
%%Plotting
figure
subplot(2,1,1);
plot(time,data)
subplot(2,1,2);
plot(time,counter_channel)

  0 Comments

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 15 Feb 2013
If you have the Image Processing Toolbox (type ver on the command line to check), you can do that in like one line or two lines with regionprops().

  0 Comments

Sign in to comment.

Sign in to answer this question.