How can I write this code lines faster?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Leonardo Restori
am 6 Dez. 2021
Beantwortet: Walter Roberson
am 6 Dez. 2021
Hi,
I need to write a double summation but with a normal cycle for I have the wrong resut.
Th5=double_summation(m,n)=1/((m^2/a^2)+(n^2/b^2))^2
m=(1,3,5); n=(1,3,5).
for m=(1:2:5)
for n=(1:2:5)
summation(m,n)=1/((m^2/a^2)+(n^2/b^2))^2;
end
end
To get the corret solution I wrote the entire summation like this, but I can't figure out the problem with the cycle.
S1=1/((1/a^2)+(1/b^2))^2;
S3=S1+(1/((3/a^2)+(1/b^2))^2)+(1/((1/a^2)+(3^2/b^2))^2)+(1/((3^2/a^2)+(3^2/b^2))^2);
S5=S3+(1/((1/a^2)+(5/b^2))^2)+(1/((5^2/a^2)+(1/b^2))^2)+(1/((3^2/a^2)+(5^2/b^2))^2)+(1/((5^2/a^2)+(3^2/b^2))^2)+(1/((5^2/a^2)+(5^2/b^2))^2);
If anyone could help me I would be grateful.
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 6 Dez. 2021
Your code works, but it leaves 0s inside the array because it never assigns to even rows or columns. But the zeros do not matter if you are just going to sum() the results.
For faster execution vectorize.
m=(1:2:5).'
n=1:2:5
s=1./((m.^2./a.^2)+(n.^2./b.^2)).^2;
sum(s(:))
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!