2017-03-17 1 views
0

문자열 배열의 셀 배열이 있고 20 %, 셀의 문자열 총 수의 30 %처럼 A와 B를 셀 배열의 비율로 바꿔야합니다. 예를 들어 어레이 :문자열의 셀 배열에서 두 문자 바꾸기

A_in={ 'ABCDE' 
     'ACD' 
     'ABCDE' 
     'ABCD' 
     'CDE' }; 

이제, 우리는 A (2/5 서열) 서열에서 40 %의 A와 B를 교환 할 필요가있다. A와 B를 포함하지 않는 시퀀스가 ​​있으므로 건너 뛰기 만하면 AB를 포함하는 시퀀스를 바꿀 것입니다. A의 픽업 시퀀스는 무작위로 선택됩니다. 적절한 방법을 누군가에게 알려줄 수 있습니다. 예상 출력은 다음과 같습니다

A_out={ 'ABCDE' 
      'ACD' 
      'BACDE' 
      'BACD' 
      'CDE' } 

답변

1

strrep

% Input 
swapStr = 'AB'; 
swapPerc = 0.4; % 40% 

% Get index to swap 
hasPair = find(~cellfun('isempty', regexp(A_in, swapStr))); 
swapIdx = randsample(hasPair, ceil(numel(hasPair) * swapPerc)); 

% Swap char pair 
A_out = A_in; 
A_out(swapIdx) = strrep(A_out(swapIdx), swapStr, fliplr(swapStr)); 
1

당신처럼, strfind를 사용할 수 있습니다로 randsample과 스왑으로 임의 퍼센트 인 인덱스를 가져

A_in={ 'ABCDE'; 
    'ACD'; 
    'ABCDE'; 
    'ABCD'; 
    'CDE' }; 
ABcells = strfind(A_in,'AB'); 
idxs = find(~cellfun(@isempty,ABcells)); 
n = numel(idxs); 
perc = 0.6; 
k = round(n*perc); 
idxs = randsample(idxs,k); 
A_out = A_in; 
A_out(idxs) = cellfun(@(a,idx) [a(1:idx-1) 'BA' a(idx+2:end)],A_in(idxs),ABcells(idxs),'UniformOutput',false); 
관련 문제