【问题标题】:Optimize for loop for large matrix in MATLAB优化 MATLAB 中大矩阵的循环
【发布时间】:2013-03-01 02:31:48
【问题描述】:

我有一个非常大的矩阵 (750000 x 6),其中有一列股票价格的时间。时间间隔不统一,因此我插入了新的时间。由于我只想包括工作日工作时间内的时间,因此我有一个 for 循环来检查插值时间是否在其中,并将这些条目复制到一个新矩阵中。但是,我的程序需要永远运行(> 10 分钟)。这是我的原始代码:

A = IBM;
times = A(:,1);
incr = t;
uniqday = datevec(times);
uniqday = unique(uniqday(:,1:3), 'rows'); % unique days for data

% Computes interpolated prices at sampling interval
interptimes = (times(1):incr:times(end)).';      

% Fractional hours into the day
frac_hours = 24*(interptimes - floor(interptimes));    
% Exclude interpolated times outside of trading hours
newtimes = interptimes((frac_hours > 0) & (frac_hours < 19.1)); 

% Exclude weekends & holidays
newtimesvec = datevec(newtimes);
newtimesvec2 = zeros(length(newtimesvec),6);
for j = 1:length(uniqday)
    for i = 1:length(newtimesvec)
        if newtimesvec(i,1:3) == uniqday(j,:)
              newtimesvec2(i,:) = newtimesvec(i,:);
        else       %Program always get stuck at this line
        end
    end
end

所以我想也许删除插值时间数组中的条目会更快,而不是复制到新矩阵,但是当一个条目被删除时,插值时间数组会改变大小,所以这个 for 循环会导致它访问外部矩阵。我不确定如何解决这个问题。

for i = 1:length(interptimes)
    for j = 1:length(uniqday)
        if interptimes(j,1:3) == uniqday(j,:)
        else
            interptimes(j,:) = [];
        end 
    end
end

【问题讨论】:

    标签: matlab optimization for-loop


    【解决方案1】:

    您可以只使用ismember 来查找uniqday 中的日期:

    newtimesvec2 = newtimesvec(ismember(newtimesvec(:,1:3),uniqday,'rows'),:);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多