How to replace non consecutive value on a vector?
显示 更早的评论
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!
采纳的回答
更多回答(2 个)
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
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)
类别
在 帮助中心 和 File Exchange 中查找有关 Coordinate Reference Systems 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!