조회 수: 2 (최근 30일)
CC SS . 2023년 9월 24일
편집: Matt J . 2023년 9월 24일
If I use function to calculate the double summation for , the code is
n = 100;
a = @(p) sin(p);
sum(sum(a(0:n)' * a(0:n)))
However, if I want to calculate the quadruple summation , how to modify the code?
##### 댓글 수: 4이전 댓글 3개 표시이전 댓글 3개 숨기기
Dyuman Joshi 2023년 9월 24일
Good point, @Matt J

댓글을 달려면 로그인하십시오.

### 답변 (2개)

Matt J 2023년 9월 24일
편집: Matt J 님. 2023년 9월 24일
n = 100;
tic;
sum(sin(0:n))^4;
toc
Elapsed time is 0.002355 seconds.
##### 댓글 수: 0이전 댓글 -1개 표시이전 댓글 -1개 숨기기

댓글을 달려면 로그인하십시오.

Steven Lord 2023년 9월 24일
이동: Matt J 님. 2023년 9월 24일
You could use implicit expansion to avoid having to create quite so many large arrays. It's not as fast as the case that exploits the separability, but it is significantly faster than the original general approach.
%Random value for N for example
N = 100;
kvec = 0:1:N; %1 as increment is not necessary
tic
[p,q,r,s] = ndgrid(kvec);
arr = sin(p).*sin(q).*sin(r).*sin(s);
s1 = sum(arr,'all');
toc
Elapsed time is 3.802691 seconds.
tic
s2=sum(sin(kvec))^4;
toc
Elapsed time is 0.002488 seconds.
% Use implicit expansion
tic
n = numel(kvec);
sinK = sin(kvec);
p = reshape(sinK, n, 1, 1, 1); % unnecessary in this case, but useful for generality
q = reshape(sinK, 1, n, 1, 1);
r = reshape(sinK, 1, 1, n, 1);
s = reshape(sinK, 1, 1, 1, n);
s3 = sum(p.*q.*r.*s, 'all');
toc
Elapsed time is 0.332431 seconds.
The trailing 1's in the reshape calls aren't really necessary, but they do make the pattern of sizes quite easy to see.
format longg
results = [s1, s1-s2, s1-s3; s2-s1, s2, s2-s3; s3-s1, s3-s2, s3]
results = 3×3
1.0e+00 * 0.000261548679431158 -2.30172814402047e-13 0 2.30172814402047e-13 0.00026154867966133 2.30172814402047e-13 0 -2.30172814402047e-13 0.000261548679431158
Those diagonal elements are in pretty good agreement, and all the off-diagonal elements (the differences between the approaches) are all quite small in magnitude,
##### 댓글 수: 1없음 표시없음 숨기기
Matt J 2023년 9월 24일
편집: Matt J 님. 2023년 9월 24일
tic
[p,q,r,s] = ndgridVecs(sin(0:100));
result = sum( p.*q.*r.*s , 'all');
toc
Elapsed time is 0.268219 seconds.

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!