decreasing three loops to two loops with sum

1 次查看(过去 30 天)
I have this code and want to eliminate the inner most loop and use sum
How can I do that?
thetao=1;
alfa=1;
l=1;
theta2(1:7,1:21)=0;
T=[0.01, 0.1, 0.2, 0.5, 1, 2, 5];
x=0:0.05:l;
n=0:50;
for t=1:7
for j=1:length(x)
for k=1:length(n)
theta1(t,j)=(sin((2*n(k)+1)*pi*x(j)/(2*l))*exp(-(2*n(k)+1).^2*pi^2*alfa*T(t)/(4*l^2))/((2*n(k)+1)*pi));
theta2(t,j)=theta2(t,j)+theta1(t,j);
theta(t,j)=thetao-4*thetao*theta2(t,j);
end
end
end

采纳的回答

Adam Danz
Adam Danz 2020-9-23
编辑:Adam Danz 2020-9-23
----------- Updated answer ------------------------------
Vectorize the k-loop and use sum() to define theta2.
thetao=1;
alfa=1;
l=1;
theta2(1:7,1:21)=0;
T=[0.01, 0.1, 0.2, 0.5, 1, 2, 5];
x=0:0.05:l;
n=0:50;
for t=1:7
for j=1:length(x)
theta1 = sin((2*n+1)*pi*x(j)/(2*l)).* exp(-(2*n+1).^ 2*pi^2*alfa*T(t)/(4*l^2))./((2*n+1)*pi);
theta2 = sum(theta1);
theta(t,j)=thetao-4*thetao*theta2;
end
end
To demonstrate that this produces the same values at the original version, run the block and above and then two two blocks below.
% Save the theta values above and then clear all variables
theta_version2 = theta;
clearvars -except theta_version2
% Original version
thetao=1;
alfa=1;
l=1;
theta2(1:7,1:21)=0;
T=[0.01, 0.1, 0.2, 0.5, 1, 2, 5];
x=0:0.05:l;
n=0:50;
for t=1:7
for j=1:length(x)
for k=1:length(n)
theta1(t,j)=(sin((2*n(k)+1)*pi*x(j)/(2*l))*exp(-(2*n(k)+1).^2*pi^2*alfa*T(t)/(4*l^2))/((2*n(k)+1)*pi));
theta2(t,j)=theta2(t,j)+theta1(t,j);
theta(t,j)=thetao-4*thetao*theta2(t,j);
end
end
end
Now compare the results
max(abs(theta - theta_version2),[],'all')
% ans =
% 4.4409e-16
The max difference in theta between the original and new versions is 4.4409e-16. This is due to the precision in floating point calculations explained [here].

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by