Speed Up Array Allocation
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi, All -- I have a problem containing a double sum that I am currently solving with nested for loops (below). It seems to me that there should be a good way to vectorize/otherwise speed up these calculations. On a modern workstation (Windows 10) using my data set of size [N x m], 100 iterations of this calculation takes about 7 s. Not horrible, but I need to apply this to many, many data sets, some larger, some smaller. I just don't want to leave any efficiencies on the table. Thanks, in advance.
Matt
tic
% Some preliminaries
AA = zeros(N,3);
for i = 1:N % Should be able to vectorize...?
for j = 1:m
AA(i,1) = AA(i,1) + exp((-((2*j-1)*pi/2)^2)*cV1(k)*i);
AA(i,2) = AA(i,2) + ((2*j-1)^2)*exp((-((2*j-1)*pi/2)^2)*cV1(k)*i);
AA(i,3) = AA(i,3) + ((2*j-1)^-2)*exp((-((2*j-1)*pi/2)^2)*cV1(k)*i);
end
end
vec1 = AA(:,1);
vec2 = AA(:,2);
vec3 = AA(:,3);
toc
댓글 수: 2
채택된 답변
Walter Roberson
2020년 1월 21일
j = 1 : m;
i = 1 : N;
temp = exp((-((2*j-1)*pi/2).^2)*cV1(k).*i.');
vec1 = sum(temp,2);
vec2 = sum((2*j-1).^2 .* temp, 2);
vec3 = sum((2*j-1).^-2 .* temp, 2);
추가 답변 (1개)
Andrey Porokhnyuk
2020년 1월 21일
편집: Andrey Porokhnyuk
2020년 1월 22일
in the past (arount the year 2008) I was speaking with a coworker, who found that functions written in separate files are executed much faster. He was solving nonlinear LLG problems, and it seemed like giving a good boost. can not confirm it because I was using octave and scilab from that time, things are different there.
In Octave I would try declaring types explicitly before allocating elements. just think about it rationally - automatic vectors used for general mat type have pages long templates, so the memory structure should be quite complex. when you have simple int's doubles and singles, interpretter knows exactly how many bytes are necessary for every element from the beginning. It may help cutting corners.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!