0

I have an algorithm whose intermediate step is to replace a substring with another substring. To be precise I have a string HBIN_NEW and I have another string P. I want to replace every 6th,7th,8th element of the string HREP with the 1st,2nd,3rd element of PBIN_NEW. For this i have written the code

     For example If PBIN_NEW='1111111101010101' and HBIN_NEW='1111100010101010' 
   then the new string HREP
   should be HREP='1111111110101101' 
      for k=1:8:262144*8
   HREP=strrep(HBIN_NEW,HBIN_NEW(k+5:k+7),PBIN_NEW(k:k+2));
end

Is this code correct to implement the above idea. And if yes, it is taking a long time do this replacement scheme, can somebody suggest some optimized way of doing this.

0

1 Answer 1

2

The wording on the question is still a bit awkward, and I'm not exactly sure how to get the example HREP given the wording, but most likely strrep is overkill for what it sounds like you are trying to do. A simple loop with assignments would be fine:

HREP = HBIN_NEW;
for k=1:8:length(HBIN_NEW)
   HREP(k+5:k+7) = PBIN_NEW(k:k+2);
end

Often times though it can be better to just enumerate the position assignments and avoid the loop. So instead you have something like this:

HREP = HBIN_NEW;
HREP(6:8:end) = PBIN_NEW(1:8:end);
HREP(7:8:end) = PBIN_NEW(2:8:end);
HREP(8:8:end) = PBIN_NEW(3:8:end);

I think that does what you want, or should get you close enough ...

Finally, a bit of unsolicited style advice. Although Matlab doesn't have a very strict code style guide, most likely the use of all caps with underscores is not the best way of naming your variables. I personally prefer lowercase with underscores, e.g. pbin_new and only use capitalized words for constants ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.