Matlab 使用NaN预分配矩阵的索引循环中的下标分配维度不匹配
我正在使用一个气象数据集,需要从许多csv文件中提取一列,并将结果编译成一个新文件。我让它工作了一个月,但是当脚本遇到一个较短的月份(下标的赋值维度)时,它就卡住了 不匹配)。有道理,但是,我希望它只保留最初存在于占位符矩阵D中的NaN值 这是脚本的问题部分Matlab 使用NaN预分配矩阵的索引循环中的下标分配维度不匹配,matlab,loops,csv,indexing,nan,Matlab,Loops,Csv,Indexing,Nan,我正在使用一个气象数据集,需要从许多csv文件中提取一列,并将结果编译成一个新文件。我让它工作了一个月,但是当脚本遇到一个较短的月份(下标的赋值维度)时,它就卡住了 不匹配)。有道理,但是,我希望它只保留最初存在于占位符矩阵D中的NaN值 这是脚本的问题部分 %Convert dates to matlab date numbers and get number of rows Date = datenum(Date{1, 1}, 'dd-mm-yyyy'); T = size(Date, 1)
%Convert dates to matlab date numbers and get number of rows
Date = datenum(Date{1, 1}, 'dd-mm-yyyy');
T = size(Date, 1);
%# Preallocate a matrix to hold all the data, and add the date column
D = [Date, NaN(T, NumFile)];
%# Loop over the csv files, get the eleventh column and add it to the data matrix
for k = 1:NumFile
FileList = dir('*.csv');
NumFile = size(FileList,1);
filename = FileList(k).name;
disp(filename);
%# Get the current file name
CurFilePath = filename;
%# Open the current file for reading and scan in the second column using numerical format
fid1 = fopen(CurFilePath, 'r');
CurData = textscan(fid1, '%*s %*s %*s %*s %*s %*s %*s %*s %f %*[^\n]', 'Delimiter', ',"', 'HeaderLines', 17, 'MultipleDelimsAsOne',true);
fclose(fid1);
%Add the current data to the cell array
D(:, k+1) = CurData{1, 1};
end
那么,如何将较短的月份强制为31天-月份的大小,以适合占位符矩阵D。当您在一维中使用冒号运算符分配
D
时,Matlab必须假设您正在分配行中的所有元素。要解决这个问题,只需将冒号替换为1:numberOfDaysInMonth
。这样,Matlab将只指定指定的值的数量,其余值保持不变,在本例中为Nan
numberOfDaysInMonth
您可以计算为size(CurData{1,1},1)
总之,将脚本最后一行旁边的内容与以下内容交换:
%Add the current data to the cell array
numberOfDaysInMonth = size(CurData{1, 1},1);
D(1:numberOfDaysInMonth, k+1) = CurData{1, 1};