How to replace non consecutive value on a vector?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
aposta95
el 31 de Mayo de 2022
Editada: the cyclist
el 31 de Mayo de 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!
0 comentarios
Respuesta aceptada
Image Analyst
el 31 de Mayo de 2022
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.
0 comentarios
Más respuestas (2)
Davide Masiello
el 31 de Mayo de 2022
Editada: Davide Masiello
el 31 de Mayo de 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 = replacePattern(A,[5,4,4,5],[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
0 comentarios
the cyclist
el 31 de Mayo de 2022
Editada: the cyclist
el 31 de Mayo de 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)
0 comentarios
Ver también
Categorías
Más información sobre Biological Physics en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!