user2129506
user2129506

Reputation: 131

Replace sequence of integers in vector by single number

Let A be vector of integers in which I want to replace a sequence of numbers by a precise number.

Example:

A = [ 8 7 1 2 3 4 5 1 2 3 4 5 6 7 ]

and I want to replace the sequence 1 2 3 by 9.

The result would be:

B = [ 8 7 9 4 5 9 4 5 6 7 ]

Any advice?

Upvotes: 3

Views: 95

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

You can abuse strrep for your array of integers:

%// 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

As in Divakar's answer strrep and strfind are actually supposed to be used for string manipulation, but they work like a charm also for numerical arrays. I suppose internally they work with the ASCII representation (or other encoding) anyway and just return the output values in the same class as the input values. For our advantage.

Upvotes: 4

Divakar
Divakar

Reputation: 221504

This could be one approach with strfind and 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

Upvotes: 3

Related Questions