how can I increase the performance of this loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
nPts = 15;
a = linspace(0.1, 2.0, nPts);
b = linspace(0.1, 2.0, nPts);
c = linspace(0.1, 2.0, nPts);
d = linspace(-0.3, 2.0, nPts);
e = linspace(-0.3, 2.0, nPts);
f = linspace(-0.3, 2.0, nPts);
res = zeros(length(a)*length(b)*length(c)*length(d)*length(e)*length(f), 2);
idx = 1;
for i=a
for j=b
for k=c
for l=d
for m=e
for n=f
C = [i l m; l j n; m n k];
% do somthing with C and store a row in "res"
detF = sqrt(det(C));
if detF<0.001
res(idx,:)=NaN;
else
Cbb = detF^(-2/3).*C;
res(idx, 1) = trace(Cbb);
res(idx, 2) = trace(inv(Cbb));
end
% increment counter
idx = idx +1 ;
end
end
end
end
end
end
%remove the rows with NaN's
The above code works, but is probably not a good implementation.
How can I increase the performance of this code? My objective is to build all combinations of the elements in the vectors a,b,c,d,e,f , then built a symmetric matrix for each combination as shown, compute the first two principal invariants of the (scaled matrix), and store it in a result variable and visualize it finally in a scatter plot.
댓글 수: 2
Stephen23
2023년 7월 11일
"How can I increase the performance of this code?"
Perhaps by changing the part labeled 'do somthing with C and store a row in "res" so that it can process arrays:
or rewriting it using more efficient code practices:
Or perhaps by using parallel processing, or lots of other ways... without knowing the details of what that "somthing" is, we can't do much more for you.
채택된 답변
Steven Lord
2023년 7월 11일
nPts = 15;
a = linspace(0.1, 2.0, nPts);
b = linspace(0.1, 2.0, nPts);
c = linspace(0.1, 2.0, nPts);
d = linspace(-0.3, 2.0, nPts);
e = linspace(-0.3, 2.0, nPts);
f = linspace(-0.3, 2.0, nPts);
sizeOfResult = [nPts^6, 1]
So you want all 11.4 million results? If you're using release R2023a or later, take a look at the combinations function.
results = combinations(a, b, c, d, e, f);
size(results)
Let's look at the first couple rows of results
head(results)
If you need them as a numeric array rather than as a table:
data = results.Variables;
head(data)
Without knowing more about what the "somthing" you want to do is I'm not sure how much more we'll be able to suggest. With this approach you may be able to use parfor to parallelize operating on each row of this data.
Alternately you could reshape the columns of data then use those columns to create a 3-by-3-by-11390625 array and finally use some of the page-based functions (like pageeig) to operate on each of the pages of that array.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!