Adding rows to matrix conditionally

조회 수: 2 (최근 30일)
HOl
HOl 2020년 3월 31일
댓글: HOl 2020년 4월 1일
I have long datafiles that I need to alter and cannot figure out how to do this.
The simplified version of what I'm trying to do is:
x = 1 20
3 50
6 10
Column 1 is time (t) (sec 1, 3, 6) and col 2 the values.
I want to create a new matrix with time axis with 1 sec interval and that the values (col 2) are repeated until next (t) ( in col1)
The resulting matrix should be:
x2 = 1 20
2 20
3 50
4 50
5 50
6 10
Sorry about the elementery question, I'm a newby
  댓글 수: 1
Star Strider
Star Strider 2020년 3월 31일
I will defer to Guillaume’s Answer, since he posted the solution first. The data file is attached.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2020년 3월 31일
We don't have enough details to give you a complete answer but what you want to do should be easily done by
  • reading your file as a timetable. Could be as easy as:
data = readtimetable(yourfile);
depending on the actual file
  • retime the timetable to 1 second interval, which is simply:
resampled = retime(data, 'secondly', 'previous'); %retime in one second interval using the previously known value for the missing times
  • save into a new file
writetimetable(resampled, 'newfile.csv');
for example
  댓글 수: 6
Guillaume
Guillaume 2020년 4월 1일
You can construct a new time vector starting at the time of your choosing and pass that to retime instead of letting it construct it:
newtimes = (tdata.DateTimeUnified(1):seconds(30):tdata.DateTimeUnified(end)+seconds(30))';
resampled = retime(tdata, newtimes, 'previous');
HOl
HOl 2020년 4월 1일
Excellent, that works. Thank you very much!!
For any other newby's out there with wonky data here is the final code:
>> opts = detectImportOptions('data.csv'); %have to use import options because of the wonky format of the file
>> opts = opts.setvartype(3, 'char');
>> data = readtable('data.csv', opts); %import as table
>> data.(3) = duration(strrep(data.(3), ' PM', '')); %get rid of the useless PM, then convert to duration
>> data.DateTimeUnified = data.(2) + data.(3) + seconds(data.(4) / 1e6); %convert microseconds to seconds and add the whole lot
>> data.DateTimeUnified.Format = 'dd MMM yyyy HH:mm:ss.SSSSSS';
>> data(end, :) = []; %get rid of the last row which is nonsense
>> tdata = table2timetable(data, 'RowTimes', 'DateTimeUnified'); %convert to timetable
>> newtimes = (tdata.DateTimeUnified(1):seconds(30):tdata.DateTimeUnified(end)+seconds(30))';
>> resampled = retime(tdata, newtimes, 'previous');

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2020년 3월 31일
out = [(x(1,1):x(end,1))',repelem(x(:,2),[diff(x(:,1));1])];

카테고리

Help CenterFile Exchange에서 Data Preprocessing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by