Avoid for loop which has an if-statement in it
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a for-loop process, in which I have to check sth, so I have a if statement. How can I avoid for-loop to have a faster code:
for i=1:n
score = find sth in a cell array
if ~isempty(score)
M(i)=score;
do sth;
end
end
in the above code, I try to find sth in a cell array and if I find it then the score is not empty, and then fill an array M and do some other things.
Thank you
6 commentaires
Matthew Eicholtz
le 30 Mar 2016
Also, how are i and j involved in the following two lines?
str = "independent of this code"
score = features_score(strcmp(str,features_score(:,1)),2);
Réponses (2)
Guillaume
le 30 Mar 2016
Modifié(e) : Guillaume
le 30 Mar 2016
Well, str can't be independent of the loop otherwise your code just repeat the exact same thing m x n times.
Assuming str is an m x n cell aray of strings, you can use ismember to replace the loops:
%demo data;
str = {'a', 'b', 'cc'; 'ff', 'notpresent', 'ddd'};
features_score = {'a', 100; 'b', 200; 'cc', 300; 'ddd', 400; 'e', 500; 'ff', 600};
[ispresent, row] = ismember(str, features_score(:, 1));
M = zeros(size(str));
M(ispresent) = [features_score{row(ispresent), 2}]
1 commentaire
Jan
le 31 Mar 2016
Avoiding FOR loops is often overestimated. Loops are not a general problem in Matlab. They can be accelerated as in all computer languages by avoiding repeated calculations inside the loops. If this matters in your case cannot be seen as long as you post some abstract pseudo-code only. This simply hides the interesting and important details.
As usual it is not worth to accelerate the loops, if they do not consume the main part of the computing time. So use the profile command to identify the bottleneck at first and care about this only. And acceleration of 100% of a piece of code, which needs only 2% of the total processing time, reduces the run time by only 1%.
I suggest to do both: Use the profile at first, and then post the relevant code in the forum - as real code with useful test data, not as pseudo code.
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!