How to store all the T values from this nested loop?

2 views (last 30 days)
T1=80; a=5; b=4;
for n=1:5
for x=1:5
y=1:4;
T(x,y)=(4*T1/pi)*(sin((2*n-1)*(pi*x/a))/(2*n-1)*sinh((2*n-1)*(pi*y)/a)/sinh((2*n-1)*(pi*b)/a));
end
end
  1 Comment
John D'Errico
John D'Errico on 3 Mar 2018
Do you want to SUM over n?
The nested loop that you wrote will not even come close to a sum in that case.

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 3 Mar 2018
Edited: John D'Errico on 3 Mar 2018
Assuming that you wanted to sum over the values of n (which is the only thing that seems to make sense here)
In an older release of MATLAB, I might have written this as
T1=80; a=5; b=4;
[x,y] = ndgrid(1:5,1:4);
T = zeros(size(x));
for n = 1:5
T = T + (4*T1/pi)*(sin((2*n-1)*(pi*x/a))./(2*n-1).*sinh((2*n-1)*(pi*y)/a)/sinh((2*n-1)*(pi*b)/a));
end
T
T =
6.6567 16.505 36.12 71.671
10.524 25.047 47.86 74.706
10.524 25.047 47.86 74.706
6.6567 16.505 36.12 71.671
1.4076e-15 3.597e-15 9.1745e-15 6.2371e-14
Without looking at your code, I was surprised at the effective zeros on the last line, but then I looked slightly more carefully, and I see they arise from the term sin(2*n-1)*(x/a)). When x=5, we get zero.
In a newer (thus current) release, I might have written it differently.
T1=80; a=5; b=4;
x = (1:5).';
y = 1:4;
T = zeros(size(x));
for n = 1:5
T = T + (4*T1/pi)*(sin((2*n-1)*(pi*x/a))./(2*n-1).*sinh((2*n-1)*(pi*y)/a)/sinh((2*n-1)*(pi*b)/a));
end
T is the same as before, but it used implicit expansion of the vectors, thus allowing me to avoid the ndgrid call.
If I wanted to avoid the explicit loop completely, this is also quite easy.
T1=80; a=5; b=4;
x = (1:5).';
y = 1:4;
n = reshape(1:5,[1 1 5]);
T = (4*T1/pi)*(sin((2*n-1).*(pi*x/a))./(2*n-1).*sinh((2*n-1).*(pi*y)/a)./sinh((2*n-1).*(pi*b)/a));
T = sum(T,3);
Note here my careful use of the .* and ./ operators where needed. So T was originally created as a 5x4x5 array. Then I summed over the third dimension. I could have written that in one line, thus
T = sum((4*T1/pi)*(sin((2*n-1).*(pi*x/a))./(2*n-1).*sinh((2*n-1).*(pi*y)/a)./sinh((2*n-1).*(pi*b)/a)),3);
but that would have been less clear what I did.
In any event, again we see the same sum for T.
T
T =
6.6567 16.505 36.12 71.671
10.524 25.047 47.86 74.706
10.524 25.047 47.86 74.706
6.6567 16.505 36.12 71.671
1.4076e-15 3.597e-15 9.1745e-15 6.2371e-14
Be careful when writing expressions as I have done this, by expanding things to three dimensions. Had n been VERY large and/or x and y been very large vectors, then large intermediate arrays could be generated. So if x,y,n all were in the thousands of elements, we could easily be generating 3-d arrays with billions of elements, requiring many gigabytes of memory to store.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!