How to replace non consecutive value on a vector?

3 views (last 30 days)
aposta95
aposta95 on 31 May 2022
Edited: the cyclist on 31 May 2022
Hi, I want to replace non consecutive value on a vector, for example:
A=[5,5,5,5,5,4,5,5,5,5,4,4,5,5,5,5,4,4,4,5,5,5,5];
From A, I want to replace the value 4 to 5, provided that 4 comes only once or twice.
So, I want to replace the below 4 (bold) to 5.
A=[5,5,5,5,5,4,5,5,5,5,4,4,5,5,5,5,4,4,4,5,5,5,5];
The result would be..
A=[5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,5,5,5,5];
How can find those 4s and replace them to the value I want?
I want to generalize the code to apply for another cases (not only for this 4 and 5 case)
Many thanks!

Accepted Answer

Image Analyst
Image Analyst on 31 May 2022
You can use bwareafilt if you have the Image Processing Library:
A = [5,5,5,5,5,4,5,5,5,5,4,4,5,5,5,5,4,4,4,5,5,5,5];
% Get the mode value
modeValue = mode(A)
% Find out where the array is not the mode value
mask = A ~= modeValue
% Extract only those locations where the non-mode values
% are a sequence of 1 or 2 long.
mask = bwareafilt(mask, [1, 2])
% Replace those locations with the mode value
A(mask) = modeValue
modeValue =
5
mask =
1×23 logical array
0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0
mask =
1×23 logical array
0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0
A =
Columns 1 through 20
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 4 4 5
Columns 21 through 23
5 5 5
See? Only the lengths of 4 that were 1 and 2 long were replaced by 5.

More Answers (2)

Davide Masiello
Davide Masiello on 31 May 2022
Edited: Davide Masiello on 31 May 2022
You could write a function that scans your array in search of the pattern you specify and replaces it with another.
clear
clc
A = [5,5,5,5,5,4,5,5,5,5,4,4,5,5,5,5,4,4,4,5,5,5,5];
pat = [5,4,5];
rep = [5,5,5];
A = replacePattern(A,pat,rep)
A = 1×23
5 5 5 5 5 5 5 5 5 5 4 4 5 5 5 5 4 4 4 5 5 5 5
A = replacePattern(A,[5,4,4,5],[5,5,5,5])
A = 1×23
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 4 4 5 5 5 5
function out = replacePattern(array,pat,rep)
for idx = 1:length(array)-length(pat)+1
if all(array(idx:idx+length(pat)-1) == pat)
array(idx:idx+length(pat)-1) = rep;
end
end
out = array;
end

the cyclist
the cyclist on 31 May 2022
Edited: the cyclist on 31 May 2022
Here is an absolutely terrible, obfuscated way to do this:
A = [5,5,5,5,5,4,5,5,5,5,4,4,5,5,5,5,4,4,4,5,5,5,5];
SA = char(A);
S = {char([5 4 5]);
char([5 4 4 5])};
R = {char([5 5 5]);
char([5 5 5 5])};
for nr = 1:numel(R)
SA = strrep(SA,S{nr},R{nr});
end
A = SA - char(0)
A = 1×23
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 4 4 5 5 5 5
I racked my brain for a numeric equivalent to strrep, but I couldn't remember (or find) one.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!