Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
Optimization code to avoid the repeating of the same expression
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Stephen23
2015년 11월 11일
편집: Stephen23
2015년 11월 12일
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
Stephen23
2015년 11월 13일
편집: Stephen23
2015년 11월 13일
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?
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!