Replace character in string/cell with the character above it

String/cell example: --> real string/cell is very long
a= { 'a' ; 'b' ; 'c' ; 'b'}
Wanted outcome:
a_new= { 'a' ; 'a' ; 'c' ; 'c'}

 채택된 답변

the cyclist
the cyclist 2021년 3월 11일
편집: the cyclist 2021년 3월 11일
The general rule is not perfectly clear to me, from your small example. Do you mean that you want the even-numbered elements to be replaced? If so, then
anew = a;
a(2:2:end) = a(1:2:end-1);
If not, maybe you could explain in a little more detail.

댓글 수: 3

Sorry I hope this will make it more clear.
String/cell example: --> real string/cell is very long
a= { 'a' ; 'b' ; 'c' ; 'b' ; 'h' ; 'g' ; 'b'}
Wanted outcome:
a_new= { 'a' ; 'a' ; 'c' ; 'c', 'h' , 'g' , 'g'}
Explanation outcome:
So every b wil be replaced with the character above it:
-first b by a
-second b by c
-third b by g
Here is one way:
a = { 'a' ; 'b' ; 'c' ; 'b' ; 'h' ; 'g' ; 'b'};
replace_idx = find(strcmp(a,'b'));
a_new = a;
a_new(replace_idx) = a_new(replace_idx-1);
This will not work if 'b' is the first element, so you will need to modify this algorithm in that case. But you haven't given info on what you want to do then.
Thank you so much!!
There is no b as first element, so this works perfect.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2021년 3월 11일
편집: Jan 2021년 3월 11일
Maybe:
a_new = a;
a_new(2:2:end) = a(1:2:end);
Or:
index = repelemt(1:2:numel(a), 1, 2):
a_new = a(index)
[EDITED] after your comment: "So every b wil be replaced with the character above it"
index = find(strcmp(a, 'b'));
a(index) = a(index - 1);
What about: {'a'; 'b'; 'b'} or {'b'} or {'b', 'a'}?

카테고리

태그

질문:

2021년 3월 11일

댓글:

2021년 3월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by