How to optimize this string replacement code - matlab

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.

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 ...

Related

Why are while loops not recommended in scala

The scala style checker says that while loops are deprecated if you’re using a strict functional style - http://www.scalastyle.org/rules-dev.html#org_scalastyle_scalariform_WhileChecker.
I found 1 solution - Is there any advantage to avoiding while loops in Scala?
This says mutability will ensure that, on the long run, you'll introduce bugs with a while pattern. How can this happen?
Why is there no check for for loop if immutability is highly restricted?
I have a simple use case where I have to remove all the occurrences of substring from a string that are present at the end. I could find a solution for it because of which I was using loops.
Example - String is "IABCFGHUABCABC" and subtring is "ABC". String output should be "IABCFGHU" where all the trailing occurrences of substring is removed.
Is there any non imperative and recommended way to solve this problem using scala?
Why is there no check for for loop if immutability is highly restricted?
Because unlike in C-style for loops, there's no mutability in Scala for:
for (i <- <something>) {
<body>
}
is just another way to write the method call <something>.foreach { i => <body> }.
Is there any non imperative and recommended way to solve this problem using scala?
Yes, of course. As the question you linked says, you can use tail recursion. I won't provide code, but the idea is: if the string doesn't end with the substring, return it; if it does, remove that ending and call the function again with new arguments. You should think on why this will ultimately return the desired result.

Where would custom subscripts be suited over methods/functions and why?

I've researched this in Swift and am confused on where custom subscripts are useful compared to methods and functions. What is the power in using them rather than using a method/func?
It's purely stylistic. Use a subscript whenever you'd prefer this syntax:
myObject[mySubscript] = newValue
over this one:
myObject.setValue(newValue, forSubscript: mySubscript)
Subscripts are more concise and, when used in appropriate situations, clearer in intent.
Which is an easier, clearer way to refer to an array element: myArray[1] or myArray.objectAtIndex(1)?
Would you like to saymyArray[1...3], or would it by just fine if you had to say something like myArray.sliceFromIndex(1).throughIndex(3) every time?
And hey, you know what? Arithmetic operators are also just functions. So don't we abandon them, so we'd have to say something like
let sum = a.addedTo(b.multipliedBy(c))
Wouldn't that be just the same really? What's the power in having arithmetic operators really?

Matlab: Slicing matrix inside a containers.Map always requires intermediate referencing?

Prologue:
I am in the process of designing/prototyping a piece of code in Matlab.
As at the moment it is not clear to me which matrices should be returned by my functions, I chose, as a general approach, to bind my returned values in containers.Map (as I would do e.g. in python).
Hence, the general setting is
function output = myfoo(args)
output = containers.Map;
...some stuff
output('outname1') = ...
output('outname2') = ...
end
this approach should have the advantage of allowing me to add more returned data without messing up the other code too much or break backwards compatibility.
Issue:
How to deal in a elegant way with matrix slicing?
Say that I need to do something like
output('outname1')(2:end) = ...
(which gives an error as two indexes are not allowed and a boring workaround like
temp = output('outname1')
temp(2:end) = ...
output('outname1') = temp
is required).
Question:
Is there a proficient way to deal with this, avoiding all this referencing/copying job?
No, there is no way to do it without a temporary variable. The only case in which a double index is valid in Matlab is for a cell array. In that case, you can use
output{...}(...)
However, in any other case, a double index results in an error.

Simplify boolean expression i.t.o variable occurrence

How to simplify a given boolean expression with many variables (>10) so that the number of occurrences of each variable is minimized?
In my scenario, the value of a variable has to be considered ephemeral, that is, has to recomputed for each access (while still being static of course). I therefor need to minimize the number of times a variable has to be evaluated before trying to solve the function.
Consider the function
f(A,B,C,D,E,F) = (ABC)+(ABCD)+(ABEF)
Recursively using the distributive and absorption law one comes up with
f'(A,B,C,E,F) = AB(C+(EF))
I'm now wondering if there is an algorithm or method to solve this task in minimal runtime.
Using only Quine-McCluskey in the example above gives
f'(A,B,C,E,F) = (ABEF) + (ABC)
which is not optimal for my case. Is it save to assume that simplifying with QM first and then use algebra like above to reduce further is optimal?
I usually use Wolfram Alpha for this sort of thing.
Try Logic Friday 1
It features multi-level design of boolean circuits.
For your example, input and output look as follows:
You can use an online boolean expression calculator like https://www.dcode.fr/boolean-expressions-calculator
You can refer to Any good boolean expression simplifiers out there? it will definitely help.

Scala multiline string placeholder

This question is related to ( Why is there no string interpolation in Scala? ), but deals more specifically with multi-line strings.
I've just about bought into Martin's suggestion for simple string placeholder where
msg = "Hello {name}!"
can be be represented without much difference in Scala today like this:
msg = "Hello"+name+"!"
However, I don't think that approach holds with multi-line strings. And, in some cases it may be encouraging other poor practices in favor of readability. Note that in the Scala Play ANORM database mapping how the framework tries to preserve readability in plain SQL (using placeholders), but at the expense of duplicating the {countryCode} variable name and in a non-type-safe way, see...
.on("countryCode" -> "FRA")
SQL(
"""
select * from Country c
join CountryLanguage l on l.CountryCode = c.Code
where c.code = {countryCode};
"""
).on("countryCode" -> "FRA")
Additionally, assuming no change in Scala to address this, what would be the implication of using inline XML? How would performance, memory, etc. with something like:
val countryCode = "FRA"
SQL(<c>
select * from Country c
join CountryLanguage l on l.CountryCode = c.Code
where c.code = {countryCode};
</c>.text)
A scala.xml.Elem would be constructed which had the string contents represented as an ArrayBuffer, chopped up for every { } substitution. I'm certainly no authority but I believe what would happen is that there's a little extra overhead in construction the object and then getting the children and concatenating them together at runtime but, at least in this example, as soon as it's passed to the SQL function which then extracts the string it wants (or perhaps this would be done with an implicit) the Elem object would be discarded so there'd be a little extra memory usage, but only briefly.
But in the bigger picture, I don't think it's performance that would hinder the adoption of this solution but I guess a lot of people would be uncomfortable abusing XML in this way by using a made-up tag. The problem would be with other users reading the code later trying to figure out the semantic meaning of the tag... only to find there isn't one.
The example you give is almost certainly not doing string concatenation, it's creating parameterized SQL statements (probably via JDBC's PreparedStatement).
Ironically, the lack of easy string concatenation is probably slightly encouraging best practices in this case (although I certainly wouldn't use that as an argument either way on the topic).
If you are coming to this question from the future, multi-line string interpolation is now a thing.
val when = "now"
println(s"""this is $when a thing.""")
// this is now a thing