How to extract a for loop output after each iteration?
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Rik
2024 年 3 月 29 日
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
2024 年 3 月 30 日
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.
採用された回答
Star Strider
2024 年 3 月 29 日
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!