Index through datestring, selecting whole hours

1 次查看(过去 30 天)
Hi,
i have the following problem. I have created a cell array consisting of two columns date and value, which looks like this (extract):
'02-10-2014 20:30' [10934]
'02-10-2014 21:00' [10195]
'02-10-2014 21:30' [ 9388]
'02-10-2014 22:00' [ 8808]
'02-10-2014 22:30' [ 8730]
I want to filter through the array and select only values that correspond to whole hours like:
'02-10-2014 21:00' [10195]
'02-10-2014 22:00' [ 8808]
Any suggestion please?
Many thanks
Stefan

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-10-3
编辑:Azzi Abdelmalek 2014-10-3
a={'02-10-2014 20:30' [10934]
'02-10-2014 21:00' [10195]
'02-10-2014 21:30' [ 9388]
'02-10-2014 22:00' [ 8808]
'02-10-2014 22:30' [ 8730]}
c1=datevec(a(:,1),'dd-mm-yyyy HH:MM')
idx=c1(:,5)==0
out=a(idx,:)
  1 个评论
Stefan Hristov
Stefan Hristov 2014-10-3
Many thanks Azzi,
that worked just fine! Actually i tried just datevec(a(;,1)) withoug assigning the format and it worked fine as well.
Best
Stefan

请先登录,再进行评论。

更多回答(4 个)

Image Analyst
Image Analyst 2014-10-3
Something like
counter = 1;
for row = 1 : size(ca, 1)
cellContents = ca{row, 1}; % Extract first column of this row.
if strfind(cellContents, ':00')
% Cell contains :00, so append it to the output cell array.
output_ca{counter, 1} = cellContents;
output_ca(counter, 2) = ca(row, 2);
counter = counter + 1;
end
end
That's one way at least, sort of the intuitive but brute force way. There are probably other ways that are more compact, like using cellfunc() or something. Note how I used braces and parentheses. If you don't know why, see the FAQ : http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F. You may find it easier to use a structure array than a cell array.

Andrei Bobrov
Andrei Bobrov 2014-10-3
编辑:Andrei Bobrov 2014-10-3
Z = {'02-10-2014 20:30' [10934]
'02-10-2014 21:00' [10195]
'02-10-2014 21:30' [ 9388]
'02-10-2014 22:00' [ 8808]
'02-10-2014 22:30' [ 8730]};
[~,~,~,~,m] = datevec(Z(:,1),'dd-mm-yyyy HH:MM');
out = Z(m == 0,:);
or
out = Z(~cellfun('isempty',regexp(Z(:,1),':00')),:);

Matz Johansson Bergström
编辑:Matz Johansson Bergström 2014-10-3
Another alternative where I just pick the last two characters from the first column of the cell:
%mock data:
cel{1,1} = '02-10-2014 21:00'; cel{1,2} = 3.2;
cel{2,1} = '02-10-2014 21:03'; cel{2,2} = 7.2;
mask = cellfun(@(x) strcmp(x(end-1:end), '00'), cel(:,1))
>> cel(mask,:)
ans =
'02-10-2014 21:00' [3.2000]
If you want to find out how many entries that are on the hour:
sum(mask)

Stefan Hristov
Stefan Hristov 2014-10-3
Hi all,
many thanks for your answers! I wasn't expecting that many answers so fast. It's great to see such enthusiasm in the forum as i am quite new to Matlab.
I am going through all the solutions and trying to learn. :)
Best!
Stefan

类别

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