打开特定的命名csv文件并将特定值提取到矩阵中

时间:2015-08-18 16:51:50

标签: matlab date csv

我正在尝试为yearticker的每一行打开一个csv文件,该行根据yearticker的值命名。

yearticker = {'2013K';'2011WXK';'2013HDR'} files: 2013K.csv, 2011WXK.csv, 2013HDR.csv

但我不想打开整个文件。我只想从date向量和前一天和后一天返回特定日期。

date = [20030103;20110228;20130604]

我想最终得到像这样的矩阵M,并为日期向量的每个事件添加一列。

M= [1 .057 .... ;0 .06;-1 .0633]

如果有人能帮助我解决这个问题,那就太棒了。不幸的是,我的matlab技能​​太低,无法为我的问题找到类似问题的解决方案。

CSV file content: Days & Daily returns Date, Return 20030101,.05 20030102,.057 20030103,.06 20030106,.06333

1 个答案:

答案 0 :(得分:0)

以下是使用MATLAB's low-level I/O的基本工作示例:

date = '20030103';

nheaderlines = 1;

tdata_left = [];
tdata_center = [];
tdata_right = [];

ii = 1;
fID = fopen('test.csv', 'r');
while ~feof(fID) % Read in lines until we get to the end of the file
    tline = fgetl(fID); % Read in the next line of data
    if ii <= nheaderlines
        % Don't need to do anything until we get past the headers
        ii = ii + 1;
    else
        tdata_left = tdata_center; % Shift previous day's data left
        tdata_center = strsplit(tline, ','); % Split line at delimiter

        if strcmp(tdata_center{1}, date) == 1 % Compare the date to your query date
            % Matched, get one more line then stop reading from the file
            tline = fgetl(fID);
            tdata_right = strsplit(tline, ',');
            break
        else
            % No match, move on to the next line
            ii = ii + 1;
        end
    end
end

fclose(fID);

% Generate the final matrix
M = [ ...
     -1 str2double(tdata_left{2}); ...
      0 str2double(tdata_center{2}); ...
      1 str2double(tdata_right{2}) ...
     ];

返回:

M =

   -1.0000    0.0570
         0    0.0600
    1.0000    0.0633

为了简化我的示例,我假设日期不能是数据文件中的第一行或最后一行。如果情况可能发生,您将需要添加一些额外的逻辑来处理这个问题。