Как получить несколько строк из столбца эффективным способом? - PullRequest
0 голосов
/ 23 мая 2019

(Требуется эффективная альтернатива для следующего кода Matlab.) Я хочу получить матрицу «данных» размера (N-60 * 60) из нижеприведенного кода Matlab.С циклом for и N с очень большим значением это занимает много вычислительного времени.Может ли кто-нибудь порекомендовать более быстрый способ получения матрицы данных.

N=10000;
a = randn(N,1);
order = 60;
for i=order:length(a)
    data(i-order+1,:) = a([i:-1:i-order+1])';
end

Спасибо!

1 Ответ

0 голосов
/ 02 июня 2019

Как сказал Сардар, предварительное распределение данных даст вам самое большое улучшение. Однако вы также можете удалить цикл for, используя умную индексацию. Комментарии должны объяснить большую часть того, что я сделал.

n = 1e6;
% Modified a to be a incrementing list to better understand how data is
% constructed
a = (1:n)';
order = 60;

%% Original code with pre allocation added
data = zeros(n-order+1, order);
for i = order:length(a)
    data(i-order+1,:) = a([i:-1:i-order+1])';
end

%% Vectorized code
% The above code was vectorized by building a large array to index into
% the a vector with.

% Get the indicies of a going down the first column of data
%   Went down the column instead of across the row to avoid a transpose
%   after the reshape function
idx = uint32(order:n);

% As we go across the columns we use the same indexing but -1 as we move to
% the right so create the simple offset using 0:-1:1-order. Then expand to
% the correct number of elements using kron
offset = kron(uint32(0:-1:1-order), ones(1, n-order+1, 'uint32'));

% Replicate the column indexing for how many columns we have and add the
% offset
fullIdx = repmat(idx, 1, order) + offset;

% Then use the large indexing array to get all the data as a large vector
% and then reshape it to the matrix
data2 = reshape(a(fullIdx), n-order+1, order);

% idx, offset, and fullIdx will take up a fair amount of memory so it is
% probably best to clear them
clear idx offset fullIdx;

assert(isequal(data, data2));

Примечание: использование uint32 не является строго необходимым, однако оно экономит использование памяти и дает небольшое улучшение производительности.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...