How to extract certain values in an array
13 views (last 30 days)
Show older comments
I have a vector containing n rows (dependent on user input) and two columns. The first column is the time every minute and the second being the power at each time. I want to find the power from 08:00 to 17:00 everyday. Picture below shows this array. I converted the char array to a double thinking it could be easier. I would have to do this for all the days in the month or could be from the 15th of one month to the 18th of the next. I also have the datenum values for the time as shown below. I feel using this would be better as it would uniquely identify each day, minute and month without using a numerical method ie using modulus to find the first two values in the cell and sprintf. I've also attached a sample of my code where SM,SD,SH,EM,ED,EH are Start month, day, hour and End Month, Day, Hour given by the user. I have a database of the weather files which contains the outside air temp by the hour from which I find the power out at each minute. Start and end time defined by the user ex 062311 meaning the 6th month, 23rd day and 11th hour.
%% Extracts Required Weather Temperature
m = floor(log10(Start));
D = mod(floor(Start ./ 10 .^ (m:-1:0)), 10);
if length(D) == 5
SM = D(1);
str = sprintf('%d%d%d', D(2), D(3));
SD= str2double(str);
str = sprintf('%d%d%d', D(4), D(5));
SH= str2double(str);
else
str = sprintf('%d%d%d', D(1), D(2));
SM= str2double(str);
str = sprintf('%d%d%d', D(3), D(4));
SD= str2double(str);
str = sprintf('%d%d%d', D(5), D(6));
SH= str2double(str);
end
%% Getting Time Values for the Plot
t1 = datetime(Year(1),SM,SD,SH,0,0);
t2 = datetime(Year(1),EM,ED,EH,1,0);
t11=datevec(datenum(t1));
t22=datevec(datenum(t2));
time_interval = etime(t22,t11)/60;
for c = 1:time_interval
time(c) = t1 +minutes(c);
end
c=datestr(time, 'mm dd HH:MM');
timestamp=datenum(c, 'mm dd HH:MM');
Thanks in Advance
2 Comments
Accepted Answer
Adam Danz
on 1 Nov 2021
Use datetime values instead of any other form of date/time. That allows you to easily index by hour etc.
% Load the data
data = load('matlab3.mat');
% Convert timestamp to datetime values
dtStamp = datetime(data.timestamp,'ConvertFrom','datenum')
% Extract the hour of each timestamp
hr = hour(dtStamp); % numeric integers 0:23
% Index hours between 8 and 17
idx = hr>8 & hr<17;
I don't know how you're planning on using the results but idx is a logical index identifying the rows of data that are between the specified hours.
4 Comments
More Answers (0)
See Also
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!