How to replace non consecutive value on a vector?
Afficher commentaires plus anciens
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!
Réponse acceptée
Plus de réponses (2)
Davide Masiello
le 31 Mai 2022
Modifié(e) : Davide Masiello
le 31 Mai 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
the cyclist
le 31 Mai 2022
Modifié(e) : the cyclist
le 31 Mai 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)
Catégories
En savoir plus sur Coordinate Reference Systems dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!