# Thread: Convert Matlab Algebraic Sol to C compatible

1. ## Convert Matlab Algebraic Sol to C compatible

So I am currently working on converting an FEM simulation which was first coded in MatLab (easy testing) into C, in order to improve frame rates, etc.

Now of course C isn't nearly as math friendly. A certain portion of the code has some fairly hairy integrals, which were solved at run time by the MatLab version. As opposed to implementing a numerical solution in C, I had the idea of producing the analytical solution (simple algebra) in Matlab and dumping this over to C. However there is some issue between notations, for example:

In Matlab the following expression:

Code:
`Ke = [ 16000/94354/a*b ]`
is equivalent to

Code:
`16000*b/(94354*a)`
note that 'b' is actually in the numerator. Now if the solution was as simple as this it would be no problem to convert, however the actual solution is an 8x8 matrix of expressions like:

Code:
```1/2*(1/2*depth/a^2/b^2/(1-NU^2)*NU+1/2*depth/a^2/b^2/(1-NU^2)*
(1/2-1/2*NU))*a^2-1/2*depth/b^2/(1-NU^2)*NU-1/2*depth/b^2/(1-NU^2)*
(1/2-1/2*NU))*b^2+(-1/2*depth/b/a^2/(1-NU^2)*NU-1/2*depth/a^2/b/(1-NU^2)
*(1/2-1/2*NU))*a^2*b+depth/(1-NU^2)*NU+depth/(1-NU^2)*(1/2-1/2*NU)```
So my question is, does anyone know exactly how the matlab notation works, or a relatively straightforward way of converting it to an equivalently evaluated C expression?

Any help is appreciated! (Note that changing the ^2 is quite easy) 2. Should be fairly simple. The operators +=*/ are used like normal. For the rest like ^, you will need to include a math library, like math.h. I don't see anything else that needs converted in your example. Maybe more code would help.

You may also want to look up how to allocate and 8x8 matrix for your needs. I had to take matlab as well, and it doesn't make you do crap. 3. (Disclaimer: I work on a product that has evolved over time from pure Matlab into pure C++, being a hybrid along the way.)

I can think of two reasons you want to convert from Matlab to C:

1. You need more speed.
2. You don't want a Matlab dependency.

The big problem with hand-converting Matlab to C code is that if you make changes to the C code, you need to backport these to your Matlab prototype base. This can be extremely difficult if not impossible. (Our now fully-C++ product STILL has oddities left over from its hybrid heritage -- as in, "Why the heck is it done THIS way? Because we needed to go back to Matlab")

If you absolutely need the speed boost, then do a hand conversion, but this will obviously be painful (as your post attests) and produce a maintenance nightmare.

On the other hand, if you simply seek independence from Matlab, just get the Matlab Compiler 4. Interestingly enough (I just found a solution). C was casting the 1s and 2s as integers, and then any division (like 1/2) rounded down to 0. So the fix was simply replacing any integer with:

'1' -> '1.'

AND it works!! Popular pages Recent additions 