How can I vectorize this Nested for loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to vectorize the inner loop but I'm not being able to.
for i = 1:NTS U(1) = 0; V(1) = 0; U(end)=1; V(end)=1;
for j = 2:NAS-1 U(j) = (b(j) * U(j-1) + a(j) * UOld(j) + c(j) * UOld(j+1)) / gamma(j); V(NAS-j+1) = (b(NAS-j+1) * VOld(NAS-j+1-1) + a(NAS-j+1) * VOld(NAS-j+1) + c(NAS-j+1) * V(NAS-j+1+1)) / gamma(NAS-j+1); end end
I've tried the following code but I get a wrong result, can someone please help me out if that?
U(2:NAS-1) = ((b(2:NAS-1) .* U(1:NAS-2) + a(2:NAS-1) .* UOld(2:NAS-1) + c(2:NAS-1) .* UOld(3:NAS)) ./ gamma(2:NAS-1)); V(NAS-1:-1:2) = ((b(NAS-1:-1:2) .* VOld(NAS-2:-1:1) + a(NAS-1:-1:2) .* VOld(NAS-1:-1:2) + c(NAS-1:-1:2) .* V(NAS:-1:3)) ./ gamma(NAS-1:-1:2));
clc clear
NTS=1; NAS=10;
U=rand(1,10)*100; V=U;
UU=zeros(1,10); VV=zeros(1,10);
Gamma=ones(1,100)*(1-10.05); a=ones(1,10)*(1-0.05); b=ones(1,10)*(1-0.15); c=ones(1,10)*(1-0.35);
UOld=U; VOld=V;
UU=U; VV=V;
for i=1:NTS
UU(2:NAS-1) = ((b(2:NAS-1) .* UU(1:NAS-2) + a(2:NAS-1) .* UOld(2:NAS-1) + c(2:NAS-1) .* UOld(3:NAS)) ./ gamma(2:NAS-1)); VV(NAS-1:-1:2) = ((b(NAS-1:-1:2) .* VOld(NAS-2:-1:1) + a(NAS-1:-1:2) .* VOld(NAS-1:-1:2) + c(NAS-1:-1:2) .* VV(NAS:-1:3)) ./ gamma(NAS-1:-1:2));
for j = 2:NAS-1 U(j) = (b(j) * U(j-1) + a(j) * UOld(j) + c(j) * UOld(j+1)) / gamma(j); V(NAS-j+1) = (b(NAS-j+1) * VOld(NAS-j+1-1) + a(NAS-j+1) * VOld(NAS-j+1) + c(NAS-j+1) * V(NAS-j+1+1)) / gamma(NAS-j+1); end
display(sum(U(2:NAS-1)'-UU(2:NAS-1)')); display(sum(V(2:NAS-1)'-VV(2:NAS-1)'));
end
display([U' UU']); display([V' VV']);
0 commentaires
Réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!