calculate values for certain indexes

2 次查看(过去 30 天)
Hello,
I have a set of data and I would like to find the total time of the data only when the set number changes. The data is shown in the picture below with the calculated time. What I'm trying to do is calculate the total time when the set# increases, if it doesnt then keep the total time same as the previous value. This is what I have so far but it's not working correctly.
lastset = 1;
timeholder = 0;
inittime = time(1);
for i = 1:length(set)
if set(i)>lastset
totaltime(i) = time(i)+timeholder;
timeholder = time(i);
lastset=set(i);
else
totaltime(i) = time(i-1);
end
end

回答(2 个)

Max Bernstein
Max Bernstein 2015-9-10
编辑:Max Bernstein 2015-9-10
I just realized part of the problem is the if line, it should be if set(i)~=lastset instead of >. Still not working quite right though
  1 个评论
Stephen23
Stephen23 2015-9-11
Please comment on your question rather than using an Answer. The Answers are for answering the question, while the comments are for commenting on it.

请先登录,再进行评论。


Image Analyst
Image Analyst 2015-9-13
I believe this does exactly what you want. It's even vectorized as a bonus!
% Create data
setNumber = [1,1,2,2,3,3,1,1,2,2,1,1,3,3]'
theTime = [1,1.1,2,2.1,3,3.1,4,4.1,5,5.1,6,6.1,7,7.1]'
% Find out which rows we need to ignore when computing total times.
timesToIgnore = [setNumber(1); diff(setNumber)] == 0
% Zero out times for those rows.
newTimes = theTime; % Initialize copy so we don't disturb the original data.
newTimes(timesToIgnore) = 0;
% Compute total times with times of same set zeroed out.
totalTime = cumsum(newTimes)
By the way, don't use time or set or any other built-in function names as variable names.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by