How to erase a specific elements for the name of string values and then replace them?
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello everyone,
I have names of values in this form:
dd_mm_yy_hh_mm_ss
for example:
Temp_06_02_24_10_39_34 = 32;
I would like to select only the number for the month (02) and replace it with the coresponding name of month in order to creat new value, for example:
Temp_Feb = 32;
How can I do this ?
Best regards, Ahmad
채택된 답변
Adam Danz
2024년 4월 17일
편집: Adam Danz
2024년 4월 17일
Assumptions:
- "Temp_06_02_24_10_39_34 = 32"; is a string
- This is not a variable name
- The month is in the 2nd numeric position (02, above)
- The goal is to replace the entire day_month_year_hour_minute_second datetime with the 3-letter abbreviation for the month.
str = "Temp_06_02_24_10_39_34 = 32;";
% Extract the month number and convert to short month name
[~,dtParts] = regexp(str, '_(\d+)','match','tokens');
monthStr = month(datetime(str2double([dtParts{:}])),'shortname');
% Replace the datetime portion with the short month name
newStr = regexprep(str, '(_\d+){6}',['_',monthStr{1}])
댓글 수: 4
Stephen23
2024년 4월 18일
Here is an approach using a dynamic regular expression. This avoids the extra REGEXP and MONTH function calls.
str = "Temp_06_02_24_10_39_34 = 32;";
fnh = @(s)char(datetime(s,'InputFormat','_dd_MM_yy_hh_mm_ss','Format','MMM'));
new = regexprep(str,'(_\d+){6}','_${fnh($0)}')
추가 답변 (1개)
Jon
2024년 4월 17일
I would suggest in general that you not embed the date time data in the variable name. Instead use a table, timetable, or some other data structure to hold these values along with the temperatures. Here's a little example using just a MATLAB table
% Make example table to hold data
yyyy = [2023,2023,2023,2024]'
mm = [8,4, 2, 3 ]'
dd = [15,18,6, 2]'
hh = [9,13,8,23]'
mi = [15,18,59,42]'
sec = [11,22,19,49]'
T = [29,15.3,22, 36.4]'
time = datetime(yyyy,mm,dd,hh,mi,sec);
Tdata = table(time,T)
% Find the temperature for February (month = 2)
idl = month(Tdata.time) == 2;
Tdata.T(idl)
댓글 수: 9
Jon
2024년 4월 17일
Here is an approach for extracting the month from a string with day month year ..and then creating a new string with just the month
s1 = 'Temp_15_05_24_10_44_22'
time = datetime(s1(6:end),'InputFormat','dd_MM_yy_HH_mm_ss')
mname = month(time,"shortname");
s2 = "Temp_" + mname{1}
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!