Plug Intermediate Variables into Equation - excel

I have a MATLAB symbolic math script that calculates a couple really large matrices for me, which I then convert into a function via matlabFunction. The problem is that the matrices contain integrals, and when matlabFunction converts it it creates loads of intermediate functions (about 200, which is why I'm trying not to do this manually) which contain the variable I'm integrating over, causing errors because the variable isn't defined outside the integral() call. In the end I'm left with a bunch of nested equations that look like:
M = integral(#(s)f(t1,t2,t3,t4)) <-- t1 = g(et1,et2,et3,....) <-- et3 = h(s)
They're not all functions of every other one, but theres a lot of dependencies between them becuase of how MATLAB tried to simplify the expression. The error gets thrown when MATLAB tries to evaluate et3, notices it has an s in it (which is find to be in M because of the integral), then breaks because s isn't defined.
So far I've tried messing with the commands in MATLAB to make them stop generating terms like that but everything I did seemed to make it worse, so I've moved to excel where my current idea is something like:
Start with each equation in it's own cell
Break each cell at "=" to get the actual equations on their own
Find each placeholder variable and substitute the actual expression in
I've been trying to write a macro or lambda function for this (admittedly I don't really know how to do either of those well) but I keep getting stuck because I basically need the script to take a list of variables I want to get rid of and just keep substituting until they're all gone, but I'm not really sure how to do this in Excel.
I've also tried to use a couple "multiFindAndReplace" scripts online that let you find and replace vectors of data but none of them seem to work for this case and the SUBSTITUTE command would end up needing to be nested dozens of time to get it do what I want.
Does anyone have ideas on what to do here? Or is there a setting I'm missing in MATLAB to suppress all the intermediate terms?
EDIT: As soon as I posted this I had another idea - it looks like MATLAB generates the terms such that the et terms can't depend on one another and that no et term appears in more than one t term.
(also this is my first question, let me know if I put it in the wrong place)

Related

TypeError: src data type = 23 is not supported

hope you're all having a great day so far.
I have a python 3.6 script that applies random (well, in fact it's more like exhaustively all existing) sequences of image transformations with openCV to an image, compare it to a seeken result and try the next one.
Image transformations include:
Thresholding
Morphological transformation
Smoothing
Playing with colors (with cvtColor, but also hand-made algorithm)
Playing with gradients
I won't show the code for this since it's basically just a heavy set of loops and arrays, which I think couldn't be linked to my issue.
Obviously enough most of the tried combinations aren't valid ones since, for example, converting BGR to GRAY might not work well if done after a conversion from BGR to GRAY. I know it's not very pythonic of me, since opposed to EAFP thinking, but since exception-catching cost a lot and happened pretty often, and sometime after some heavy treatment, I wanted to add a few conditions which would prevent most of them.
To do so, I sorted my array of functions and, by checking if I'm within a certain range, I can check the validity of the transformation to come and abort if bad.
if steps[it] >= THREE_CHANNELS_LIMIT:
if len(cur_img.shape) == 3:
if steps[it] >= SINGLE_CHANNEL_LIMIT:
break
elif cur_img.dtype not in BGR_DEPTHS:
break
Where steps[it] is the index pointing to the next function to execute, and THREE_CHANNELS_LIMIT or SINGLE_CHANNEL_LIMIT are the specific index at the border of each function range.
The above code prevents single-channel transformations to be done on multi-channel numpy image.
Now with my issue : from logged exceptions, I can see a few functions, the OpenCV morphological functions, are still throwing errors.
TypeError: src data type = 23 is not supported
Which I think is probably an issue with pixel depth. However, I have no idea what type 23 is/means, and I would like to know it in order to guess how often the issue occurs and determine whether or not I should add another condition or let the try-except statement deal with it.
Searched through the web but found many type = 17, type = 18 or type = 0 issues, but can't seem to find this one.
Is there a file somewhere listing all of OpenCV types used for Error message? Or maybe one of you know about this specific one, which would do the trick for my present case?
And sorry for my innacurate english. Current speelchecker just underline everything so I might have left many typos, too.

HaxeFlixel Puyo Puyo

I've been wanting to make a block type game for a while now but have never understood how to actually make one. I have googled forever and there is not much and what is there comes with a stipulation that I am not wanting to bother with (gpl license, entire code base, AND the license in any project, bleh). So I took to a forums with my problem. I did not know it, but I was trying to make a Puyo Puyo type game. With blocks dropping from the ceiling and then clearing if there's a match of 3 or more. I had no idea on how to do the matching. Which is what I wanted to know. A very nice, charming, and intelligent fellow provided me with this:
http://hastebin.com/ziyejejoxu.js
Granted, that's quite a lot, but the way he managed to code it allowed me to somewhat grasp it. However, there is a single infuriating problem. One, exactly ONE, line of code does not compile and breaks. I asked him if I could email him about it and he said okay. I haven't go a response yet so I may not be getting one so I'm taking this here. Here is how I am using the code so far. There are two parts, the play state, and the puzzle piece:
http://pastebin.com/SvMR9mMb
The program breaks in the playstate, giving this error:
source/PlayState.hx:291: characters 33-52 : Array access is not allowed on x : Int -> Int
What I have tried:
I had assumed that it was not allowed because the puzzle piece x is a float, and of course, you can't push a float into an int array. So what I did was simply in the puzzle piece first, convert the the float to an int. That did not work. THEN in the state, I switched the float to an int. That did not work. As an exercise, I attempted to convert a Flixel game to HaxeFlixel to see if I could learn anything. I probably did it wrong and did not.
So the question is: Why does that line not compile and what do I need to do to make it compile or to achieve it's intended purpose?
The syntax is wrong. push is a function, and function calls use (). [] is for array access (hence the error message).
This should work:
if (this_piece_is_in_a_match) matched_pieces.push(_i);

Shorter version of IF(ISERROR(...))

I'm wondering if there is a way to check if a formula returns an error, and if not, use the value found, without doing the following:
=IF(ISERROR(A1/B1), 0, A1/B1)
The syntax I'm looking for is something like this:
=EQ([value_if_not_error], [value_if_error])
The solution might contain more stuff, IF and ISERROR is perfectly fine, as long as I avoid having the main function several times in each cell. The reason why I want to do this is that my equations are quite long and the readability is drastically reduced when I have to write the equation twice, or even more (if several ifs).
Is there a simple solution to this?
Try
=IFERROR([formula], [value_if_error])

Manipulating/Clearing Variables via Lists: Mathematica

My problem (in Mathematica) is referring to variables given in a particular array and manipulating them in the following manner (as an example):
Inputs: vars={x,y,z}, system=some ODE like x^2+3*x*y+...etc
(note that I haven't actually created variables x y and z)
Aim:
To assign values to the variables in the list "var" with the intention of inputting these values into the system of ODEs. Then, once I am done, clear the values of the variables in the array vars so that it is in its original form {x,y,z} (and not something like {x,1,3} where y=1 and z=3). I want to do this by referring to the positional elements of vars (I aim not to know that x, y and z are the actual variables).
The reason why: I am trying to write a program that can have any number of variables and ODEs as defined by the user. Since the number of variables and the actual letters used for them are unknown, it is necessary to perform manipulations with the array itself.
Attempt:
A fixed number of variables is easy. For the arbitrary case, I have tried modules and blocks, but with no success. Consider the following code:
Clear[x,y,z,vars,svars]
vars={x,y,z}
svars=Map[ToString,vars]
Module[{vars=vars,svars=svars},
Symbol[svars[[1]]]//Evaluate=1
]
then vars={1,y,z} and not {x,y,z} after running this. I have done functional programming with lists, atoms etc. Thus is makes sense to me that vars is changed afterwards, because I have changed x and not vars. However, I cannot get "x" in the list of variables to remain local. Of course I could put in "x" itself, but that is particular to this specific case. I would prefer to put something like:
Clear[x,y,z,vars,svars]
vars={x,y,z}
svars=Map[ToString,vars]
Module[{vars=vars,svars=svars, vars[[1]]},
Symbol[svars[[1]]]//Evaluate=1
]
which of course doesn't work because vars[[1]] is not a symbol or an assignment to a symbol.
Other possibilities:
I found a function
assignToName[name_String, value_] :=
ToExpression[name, InputForm, Function[var, var = value, HoldAll]]
which looked promising. Basically name_String is the name of the variable and value is its new value. I attempted to do:
vars={x,y,z}
svars=Map[ToString,vars]
vars[[1]]=//Evaluate=1
assignToName[svars[[1]],svars[[1]]]
but then something likeD[x^2, vars[[1]]] doesn't work (x is not a valid variable).
If I am missing something, or if perhaps I am going down the wrong path, I'm open to trying other things.
Thanks.
I can't say that I followed your train(s) of thought very well, so these are fragments which might help you to answer your own questions than a coherent and fully-formed answer. But to answer your final 'question', I think you may be going down some wrong path(s).
In passing, note that evaluating the expression
vars = {x,y,z}
does in fact define those three variables though it doesn't define any rewrite rules (such as values) for them.
Given a polynomial poly you can extract the variables in it with the function Variables[poly] so something like
Variables[x^2+3*x*y]
should return
{x,y}
Note that I write 'should' rather than does because I don't have Mathematica on this machine so my syntax may be a bit wonky. Note also that your example ODE is nothing of the sort but it strikes me that you can probably write a wrapper to manipulate an ODE into a form from which Variables can extract the variables. Mathematica offers a lot of other functions for picking expressions apart and re-assembling them, follow the trails from Variables. It often allows the use of functions defined on Lists on expressions with other heads too so it's always worth experimenting a bit.
There are a couple of widely applicable ways to avoid setting values of variables in Mathematica. For instance, you could write
x^2+3*x*y/.{x->2,y->3}
which will evaluate to
22
but not set values for x and y. This is a very simple example of using (sets of) replacement rules for temporary assignment of values to variables
The other way to avoid setting values for variables is to define functions using Modules or Blocks both of which define their own contexts. The documentation will tell you all about these two and the differences between them.
I can't help thinking that all your clever tricks using Symbol, ToExpression and ToString are a bit beside the point. Spend some time familiarising yourself with Mathematica's in-built functionality before going further down that route, you may well find you don't need to.
Finally, writing, in any language, expressions such as
vars=vars,svars=svars
will lead to madness. It may be syntactically correct, you may even be able to decrypt the semantics when you first write code like that, but in a week's time you will curse your younger self for writing it.

Functional alternative to caching known "answers"

I think the best way to form this question is with an example...so, the actual reason I decided to ask about this is because of because of Problem 55 on Project Euler. In the problem, it asks to find the number of Lychrel numbers below 10,000. In an imperative language, I would get the list of numbers leading up to the final palindrome, and push those numbers to a list outside of my function. I would then check each incoming number to see if it was a part of that list, and if so, simply stop the test and conclude that the number is NOT a Lychrel number. I would do the same thing with non-lychrel numbers and their preceding numbers.
I've done this before and it has worked out nicely. However, it seems like a big hassle to actually implement this in Haskell without adding a bunch of extra arguments to my functions to hold the predecessors, and an absolute parent function to hold all of the numbers that I need to store.
I'm just wondering if there is some kind of tool that I'm missing here, or if there are any standards as a way to do this? I've read that Haskell kind of "naturally caches" (for example, if I wanted to define odd numbers as odds = filter odd [1..], I could refer to that whenever I wanted to, but it seems to get complicated when I need to dynamically add elements to a list.
Any suggestions on how to tackle this?
Thanks.
PS: I'm not asking for an answer to the Project Euler problem, I just want to get to know Haskell a bit better!
I believe you're looking for memoizing. There are a number of ways to do this. One fairly simple way is with the MemoTrie package. Alternatively if you know your input domain is a bounded set of numbers (e.g. [0,10000)) you can create an Array where the values are the results of your computation, and then you can just index into the array with your input. The Array approach won't work for you though because, even though your input numbers are below 10,000, subsequent iterations can trivially grow larger than 10,000.
That said, when I solved Problem 55 in Haskell, I didn't bother doing any memoization whatsoever. It turned out to just be fast enough to run (up to) 50 iterations on all input numbers. In fact, running that right now takes 0.2s to complete on my machine.

Resources