quadruple summation using function
Mostra commenti meno recenti
If I use function to calculate the double summation
for
, the code is
for 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?
, how to modify the code?4 Commenti
Dyuman Joshi
il 24 Set 2023
Spostato: Dyuman Joshi
il 24 Set 2023
Similar to my answer in a previous question of yours, use ndgrid
%Random value for N for example
N = 10;
kvec = 0:1:N; %1 as increment is not necessary
[p,q,r,s] = ndgrid(kvec);
arr = sin(p).*sin(q).*sin(r).*sin(s);
s = sum(arr,'all')
But note that this approach will be quite slow:
%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
tic
s2=sum(sin(kvec))^4;
toc
s1,s2
Matt J
il 24 Set 2023
You should be exploiting the separability of the summation,

and likewise for the quadruple sum.
Dyuman Joshi
il 24 Set 2023
Good point, @Matt J
Risposte (2)
n = 100;
tic;
sum(sin(0:n))^4;
toc
Steven Lord
il 24 Set 2023
Spostato: Matt J
il 24 Set 2023
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
tic
s2=sum(sin(kvec))^4;
toc
% 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
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]
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 Commento
You can simplify this by downloading ndgridVecs from the File Exchange,
tic
[p,q,r,s] = ndgridVecs(sin(0:100));
result = sum( p.*q.*r.*s , 'all');
toc
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!