Clear Filters
Clear Filters

How to extract a for loop output after each iteration?

24 views (last 30 days)
Dear experts,
This is a for loop I am trying to implement. I want to store the result for u after each iteration of k1, c1, and rho1. I cannot figure out a way to do it.
Can some help with that?
Thank you!
for j =1:length(k1) % k1 is a matrix 1x10
for M =1:length(c1) % c1 is a matrix 1x10
for p = 1:length(rho1) % rho1 is a matrix 1x10
%u will be a matrix 17x1000
for t =1:Nt-1
u(1,t+1)= u(1,t) + 2*k1(j)*dt*(u(2,t)-u(1,t))/(rho1(p)*c1(M)*dx1^2) + 2*(hc(t)*(Ta(t) -u(1,t))+q(t))*dt/(rho1(p)*c1(M)*dx1);
for i=2:Nx-1
u(i,t+1) = u(i,t) + (k1(j).*dt)/(rho1(p).*c1(M).*dx1^2)*(u(i+1,t) - 2*u(i,t) + u(i-1,t));
end
u(Nx,t+1) = u(Nx-1,t);
end
end
end
  2 Comments
Rik
Rik on 29 Mar 2024
Your code is not formatted, so it is difficult to read. Please edit your post.
It is hard to follow your code, but it looks like every iteration is overwriting the last.
You clearly understand indexing, why don't you use a 3D cell array to store the results? Alternatively, you can use save. What did you try?
Also, code without comments and with extremely short variable names become utterly worthless in a day or so. Nobody else can understand your code, and if you stop working on it over the weekend, you won't be able to understand it either. Do yourself a favor and explain to yourself what is happening and why. (relatedly, the code you posted doesn't show Nx is 17)
Dyuman Joshi
Dyuman Joshi on 30 Mar 2024
You could vectorize the inner most loop.
Also, have you pre-allocated the variable u?
"I want to store the result for u after each iteration of k1, c1, and rho1."
That would be a time consuming task.
Are you sure you want to save the values after each iteration and not after all the iterations?
What is the objective here? It would be helpful if you can specify what you are trying to do and provide relevant details.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 29 Mar 2024
Perhaps —
u(j,m,p,t) = ... ;
in an appropriate place in the loop.
This matrix could be huge and difficult to deal with.
Consider using the squeeze function if you want to easily eliminate any singletion dimensions that may arise if you are processing it later.
.
  16 Comments
Sanley Guerrier
Sanley Guerrier on 1 Apr 2024 at 16:05
Yes, you're right. I tried both and the result clearly shows that the norm of difference is more efficient and faster.

Sign in to comment.

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!