设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 ]
有什么建议吗?
发布于 2015-04-01 15:17:18
这可能是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
发布于 2015-04-01 15:39:34
对于整数数组,可以滥用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表示(或其他编码)一起工作,只返回与输入值相同的类中的输出值。为了我们的利益。
https://stackoverflow.com/questions/29393911
复制相似问题