How to replace non consecutive value on a vector?

조회 수: 1 (최근 30일)
aposta95
aposta95 2022년 5월 31일
편집: the cyclist 2022년 5월 31일
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!

채택된 답변

Image Analyst
Image Analyst 2022년 5월 31일
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.

추가 답변 (2개)

Davide Masiello
Davide Masiello 2022년 5월 31일
편집: Davide Masiello 2022년 5월 31일
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 2022년 5월 31일
편집: the cyclist 2022년 5월 31일
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.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by