How to generalize this code?

조회 수: 4 (최근 30일)
BN
BN 2019년 12월 19일
댓글: Adam Danz 2019년 12월 19일
Hello everyone,
Thanks to Adam Danz I have this code below in order to create a NaN cell, where data are missing and generate related dates.
here is the code:
clear all
clc
filename='Qaen.xlsx'
T = readtable(filename);
Sort = sortrows(T, 8);
Sort = Sort (:, 8:9);
dt1 = datetime([1982 01 01]);
dt2 = datetime([2018 12 31]);
allDates = (dt1 : calmonths(1) : dt2).';
allDates.Format = 'MM/dd/yyyy';
tempTable = table(allDates(~ismember(allDates,Sort.data)), NaN(sum(~ismember(allDates,Sort.data)),size(Sort,2)-1),'VariableNames',Sort.Properties.VariableNames);
T2 = outerjoin(Sort,tempTable,'MergeKeys', 1);
this code was work perfect when I have 2 columns (date and value), but in my real data set, I have some other columns. in fact, the date column was my 8 column and 9, 10, 11, and 12 are my separate values (max_temp, min_temp, rainfall, average_temp).
I want to generalize the code in order to do that and conduct my research.
in fact, I want to have 1:7 column stationary and to what this code doing for 9, 10, 11, and 12 columns.
please help me. I attached my .xlsx file many thanks

채택된 답변

Adam Danz
Adam Danz 2019년 12월 19일
편집: Adam Danz 2019년 12월 19일
Instead of removing columns from your table, keep the table all together (unless you have a really good reason not to).
Check out each line of code, what it does, etc and see in-line comments for details on what I changed / added.
Let me know if you have any questions.
filename='Qaen.xlsx'
T = readtable(filename);
[~, sortIdx] = sort(T.data); % Avoid using column numbers when indexing a table; use var-names.
Sort = T(sortIdx,:); %consider re-naming "Sort" (too close to sort() function).
dt1 = datetime([1982 01 01]);
dt2 = datetime([2018 12 31]);
allDates = (dt1 : calmonths(1) : dt2).';
allDates.Format = 'MM/dd/yyyy';
% list all missing dates
% Must have same variable name as the date column in Sort.
tempTable = table(allDates(~ismember(allDates,Sort.data)),'VariableNames',{'data'});
% merge rows
T2 = outerjoin(Sort,tempTable,'MergeKeys', 1);
  댓글 수: 2
BN
BN 2019년 12월 19일
Thank you. it's awesome. really appreciate it.
Adam Danz
Adam Danz 2019년 12월 19일
happy to learn along with ya!

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by