speed up for cycle?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
i have this for cycle.
G=Bic+dif+Ri;
for i=1:size(G);
if -h_s(i) < T < h_s(i); % if true is day
G(i)=Bic(i)+dif(i)+Ri(i); % [w/m^2] radiazione globale su una superficie comunque orientata
else
G(i)=0;
end
end
i tried pre allocating in a G=zeros(31536000) but it exceeds the max value, so i tried pre allocating in a vector G=Bic+dif+Ri; but it needs a long time. 31536000 is the size of G.
Is there a method to have a fast process? or it just depend form my PC?
thanks
1 commentaire
Adam
le 5 Déc 2017
Modifié(e) : Adam
le 5 Déc 2017
G=zeros(31536000);
would attempt to create a square matrix of 31536000 * 31536000 which is massive.
If you have 31536000 elements then you should presize as
G = zeros( 1,31536000 );
or
G = zeros( 31536000,1 );
Also:
for i=1:size(G)
is not a good way to program a loop - it will simply take the first output of size and ignore the rest. If this is what you want then:
for i=1:size(G,1)
would be a clearer way to show that. Or if G is a vector then
for i=1:numel(G)
is a lot better.
Réponses (1)
Steven Lord
le 5 Déc 2017
G=Bic+dif+Ri;
This IS your preallocation of G. After executing this line, G is at its final size. You never add nor remove an element in your for loop.
for i=1:size(G);
if -h_s(i) < T < h_s(i); % if true is day
This doesn't do what you think it does. This is equivalent to the following, with the variable name shortened to make it a bit shorter.
if (-h < T) < h; % if true is day
I'll show four examples of why this doesn't work the way you think it does.
Let T = 1, h = 2. T is between -h and h so you expect this to return true. -2 < 1 is true and true < 2 is true so it does return true.
Let T = -0.5, h = 0.75. T is between -h and h so you expect this to return true. -0.75 < -0.5 is true and true < 0.75 is false so it returns false.
Let T = 2, h = 1.5. T is not between -h and h so you expect this to return false. -1.5 < 2 is true and true < 1.5 is true so it returns true.
Let T = 2, h = 0.5. T is not between -h and h so you expect this to return false. -0.5 < 2 is true and true < 0.5 is false so it returns false.
Instead use (-h < T) & (T < h).
G(i)=Bic(i)+dif(i)+Ri(i); % [w/m^2] radiazione globale su una superficie comunque orientata
else
G(i)=0;
end
end
You can vectorize the computation using linear indexing. You've already computed the first part of your if statement, so all you need to do is reject those elements that are "out of bounds".
G=Bic+dif+Ri;
listOfNonDay = (-h < T) & (T < h);
G(listOfNonDay) = 0;
0 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays 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!