Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace characters between flags in MATLAB

Tags:

matlab

Suppose I have a char variable in Matlab like this:

x = 'hello my name $ is Sean $ Daley.';

I want to replace the first '$' with the symbol '&', and the second '$' with the symbol '#'.

Furthermore, if I have a more complicated char such that pairs of '$' repeat many times, I want to repeat the same pattern. So the following:

y = 'hello $ my $ name is $ Sean $ Daley $.$.';

would be transformed into:

'hello & my # name is & Sean # Daley &.#.'

I have tried coding this manually via for loops and while loops, but the code is just so ugly. Are there any simple functions that I can use?

like image 205
Liz Salander Avatar asked Mar 17 '26 19:03

Liz Salander


1 Answers

Since you're dealing with single characters and non-nested pairs of flags, you can easily do this with a simple call to find and some indexed replacement:

y = 'hello $ my $ name is $ Sean $ Daley $.$.';
index = find(y == '$');
y(index(1:2:end)) = '&';
y(index(2:2:end)) = '#';

And the result:

y =

    'hello & my # name is & Sean # Daley &.#.'
like image 107
gnovice Avatar answered Mar 19 '26 10:03

gnovice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!