Info
Cette question est clôturée. Rouvrir pour modifier ou répondre.
Optimization code to avoid the repeating of the same expression
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi! There is a method to compact this expressions?
matchstarts_00(k) = regexp(TrajCompact(k,1), '0.+?0'); %for '00'
matchcounts_00(k) = cellfun(@numel, matchstarts_00(k));
matchstarts_11(k) = regexp(TrajCompact(k,1), '1.+?1'); %for '11'
matchcounts_11(k) = cellfun(@numel, matchstarts_11(k));
matchstarts_22(k) = regexp(TrajCompact(k,1), '2.+?2'); %for '11'
matchcounts_22(k) = cellfun(@numel, matchstarts_22(k));
matchstarts_33(k) = regexp(TrajCompact(k,1), '3.+?3'); %for '11'
matchcounts_33(k) = cellfun(@numel, matchstarts_33(k));
matchstarts_44(k) = regexp(TrajCompact(k,1), '4.+?4'); %for '11'
matchcounts_44(k) = cellfun(@numel, matchstarts_44(k));
I have a great number of this expressions: i think there is a smart method to represent them but I don't find it. Can you help me? Thanks!
0 commentaires
Réponses (2)
Stephen23
le 11 Nov 2015
Modifié(e) : Stephen23
le 12 Nov 2015
This is easy if we don't use numbered variables (see link below to know why numbered variables usually occur in bad code). The idea is simple: use a cell array and a new loop to iterate over each of 0, 1, etc. Make sure that the cell arrays are preallocated before the loops!
V = 0:4;
C_start = cell(numel(V),maxK);
C_count = cell(numel(V),maxK);
for k = 1:maxK
for n = 1:numel(V)
rgx = sprintf('%d.+?%d',V(k),V(k));
C_start{n,k} = regexp(TrajCompact(k,1),rgx);
C_count{n,k} = cellfun(@numel, C_start{n,k});
end
end
Note that this code is untested, because you did not give any data for us to test code on. Depending on the values that are returned and saved there may be simpler structures.
You should avoid numbered variables, because if it has an index then actually make it an index rather than just part of the variable name. This is the point of the cell array. And do not be tempted to dynamically define those variable names, here are explanations why this is a bad idea:
12 commentaires
Stephen23
le 13 Nov 2015
Modifié(e) : Stephen23
le 13 Nov 2015
I have feeling that your original regular expression is not actually matching what you think it is. Do you want it to include parentheses in the matched substrings?
>> rgx = sprintf('%d.+?%d',V(k),V(k));
>> X = regexp(TrajCompact(idx),rgx,'match');
creates a cell array of the matched substrings for 0, and the sixth cell contains this:
'021(23)(12)32131231(32)(13)(23)1321(32)30'
Do you want it to include parentheses, or not?
Cette question est clôturée.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!