Include missing elements in array (matlab)
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a Matlab table called 'mytable' with two columns (Times and value). See example extract below:
I would like to detect and include the missing time stamps in the Times column and assign an empty value in the following way:
I have only figured out how to do it using the following code:
%%Creates a complete duration array
A=duration(00,00,00);
B=duration(23,59,59);
Complete_time_array=linspace(A,B,86400);
%%Compare Complete_time_array with mytable.Times values and include the missing time stamps
Times=repmat({''},length(Complete_time_array),1);
value=repmat({''},length(Complete_time_array),1);
for t=1:length(Complete_time_array)
if any(strcmp(char(Complete_time_array(1,t)),mytable.Times))==1
index=find(strcmp(char(Complete_time_array(1,t)),mytable.Times));
Times{t,1}=mytable.Times(index,1);
value{t,1}=mytable.value{index,1};
else
Times{t,1}=char(Complete_time_array(1,t));
value{t,1}='';
end
end
mynewtable=table(Times,value);
However, when working with tables that have thousands of rows, this code takes too long despite having used the 'any' and 'find' matlab functions. Does anybody know how to achieve this goal more efficiently?
댓글 수: 0
채택된 답변
Madhav Rajan
2015년 8월 7일
I understand that you want to include the missing timestamps using [] in your newtable. You can make use of the 'intersect' function to compare the durations in the complete time array with the durations in your table. You can use the below example for your reference:
%%Initalization
% This creates the Time and values array
times = duration(0, 1, 0:20)';
vals = rand(21,1);
Perform intersection with the new duration variable
newtimes = duration(0, 0, 0:120)';
result = cell(length(newtimes),1);
%get the duration, the duration's index in times and the duration's index
%in newtimes
[dur, itimes, inewtimes ] = intersect(times,newtimes);
v=num2cell(vals(itimes));
[result{inewtimes}] = deal(v{:});
newtable = table(newtimes, result);
In the above example the first section initializes the times and vals similar to your 'mytable'. The second section creates an array of newtimes which contains more duration values than the first times variable. You then find the intersection and its indices between the two time variables and then assign the values to the corresponding indices in the newtimes variable. With the indices available, you would just have to do a cell array assignment as shown above.
You can refer the following link for more information on the 'intersection' function:
Hope this helps.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!