让A
为整数向量,我想用精确的数字替换数字序列。
示例:
A = [ 8 7 1 2 3 4 5 1 2 3 4 5 6 7 ]
我希望用1 2 3
替换序列9
。
结果将是:
B = [ 8 7 9 4 5 9 4 5 6 7 ]
有什么建议吗?
答案 0 :(得分:4)
您可以滥用strrep
来获取整数数组:
%// given
A = [8 7 1 2 3 4 5 1 2 3 4 5 6 7]
seq = [1 2 3];
rep = 9;
%// substitution
B = strrep(A, seq, rep)
B =
8 7 9 4 5 9 4 5 6 7
正如Divakar's answer strrep
和strfind
实际上应该用于字符串操作,但它们也像数字数组的魅力一样工作。我想在内部他们仍然使用ASCII表示(或其他编码),只返回与输入值相同的类中的输出值。为了我们的优势。
答案 1 :(得分:3)
这可能是strfind
和bsxfun
-
pattern = [1 2 3];
replace_num = 9;
B = A
start_idx = strfind(A,pattern) %// Starting indices of pattern
B(start_idx) = replace_num %// Replace starting indices with replacement
B(bsxfun(@plus,start_idx(:),1:numel(pattern)-1))=[] %// Find all group
%// indices of the pattern except the starting indices and
%// then delete them