2017-03-17 94 views
0

我有一個字符串單元格數組,並且我想以單元格數組的百分比交換A和B,例如20%,單元格中字符串總數的30%陣列 例如:交換字符串單元格數組中的兩個字符

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

現在,我們需要交換A和B中的序列的40%A(2/5序列)。有些序列不包含A和B,所以我們只是跳過它們,我們將交換包含AB的序列。 A中的拾取序列是隨機選擇的。我適當的人可以告訴我如何做到這一點。預期的輸出是:

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

回答

1

randsample和交換獲取隨機precent指數與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,如:

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); 
相關問題