简体   繁体   中英

Optimize for loop for large matrix in MATLAB

I have a very large matrix (750000 x 6) where I have a column of time for stock prices. The time intervals are not uniform, therefore I interpolated the new times. Since I only want to include times during working hours on weekdays, I have a for loop which checks if the interpolated times are within that, and copies those entries to a new matrix. However, my program takes forever to run (>10mins). This is my original code:

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

So I thought maybe deleting the entries in the interpolated time array would be faster instead of copying to a new matrix, but when an entry gets deleted, the interpolated time array changes size, so this for loop would cause it to access outside the matrix. I'm not sure how I can fix this.

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

您可以使用ismember来查找uniqday中的uniqday

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM