Forcing variable type in MATLAB - matlab

I have variables which are of double type I want them to be float. Is there a way to force a variable to be float and not double, also, Is there a way to do it in some global way for all functions and sub functions with few lines at the start of the main function? I have many functions and they use many temporary variables and create variables that they return. Going over all of my functions and changing them will be very difficult.
My rational for this request:
I'm writing the MATLAB program in order to simulate an algorithm which I'll then implement in hardware, I want to make sure that using 32bit as the size of my signals will not cause calculation errors.

Using B=single(A) as suggested by #cbz, or defining arrays as SINGLE, such as by calling B=zeros(3,3,'single') creates "floats" in Matlab.
There is no way to globally turn Matlab into a "float" environment. Although most lower-level functions are implemented for single as well (with a few exceptions, for example those mentioned in the help to DOUBLE), many high-level builtin functions will only work with double.
In other words, you'll have to manually define your variables as single, you'll have to periodically check that the variables haven't been quietly converted to double, and in the end, your code might not work if it needs a function that isn't implemented for single yet.

The MATLAB equivalent to 'float' is 'single. You can convert using
B = single(A).
That said, your assumption that this amounts to 32-bit might need revisiting. It's not as simple as that.

Related

Modelica I/O blocks vs. Functions

Blocks and functions in Modelica have some similarities and differences. In blocks, output variables are most likely expressed in terms of input variables using equations, whereas in functions output variables are expressed in terms of input variables using assignments. Given a relationship y = f(u) that can be expressed using both notions, I am interested in knowing which notion shall you favour in which situation?
Personally,
Blocks can be better integrated in block diagrams using input/output connectors
Equations in blocks can be most likely better treated by compilers for symbolic manipulation, optimization, and evaluating analytical derivatives required for Jacobian evaluation. So I guess blocks are likely less sensitive to numerical errors in some boundary cases. For functions, derivatives are likely to be evaluated using finite difference methods, if they are not explicitly provided.
on the other hand a set of assignments in a function will be most likely treated as a single equation. The same set of assignments if expressed in terms of a larger set of equations in a block will result in a model of larger size probably leading to a decrease in runtime performance
although a block with an algorithmic section is kind of equivalent to a function with the same assignments set, the syntax of a function call is favored in couple of situations
One can establish hierarchies of blocks types and do all of sort of things of object oriented modelings. Functions are kind of limited. It is not possible to extend from a non-abstract function that contains an algorithm section. But it is possible to have (an) abstract function(s) that act(s) as (an) interface(s) out of which implemented functions can be established etc.
Some of the above arguments are dependent on the way a specific simulation environment treats a block or a function. These might be low-level details not necessarily known.
The list in your "question" is already a pretty good summary. Still there are some additional things that should be considered:
Regarding the differentiation of functions, the developer at least needs to define how often the assignments can be differentiated (here is a nice read on this), as e.g. Dymola will not do it automatically. Alternatively the differentiated function can be specified manually (here). By the way, a partial derivative can be defined as well, see Language Specification, Sec. 12.7.2.
When it is necessary to invert a function, it can be necessary to define it manually. This is described in the Language Specification, Sec. 12.8.
Also it could be important that code from a function can be inlined, which should overcome some of the issues mentioned above, see Language Specification, Sec. 18.3.
Generally I would go for blocks whenever there is no very strong reason for a function. Some that come to my mind are the need for procedural execution, or for-loops.
This is just my two cents - more opinions welcome...
You might be interested in the opposite: calling a block as if it was a function:
https://github.com/modelica/ModelicaSpecification/issues/1512
The advantage of using function syntax is that you don't need to declare + connect components:
Block b;
equation
connect(x, b.in1);
connect(y, b.in2);
connect(z, b.out1);
vs
z = Block(x, y);
Of course right now, this syntax does not exist yet. And you really want to use blocks when you can. Algorithmic blocks might as well be functions as they are shorter and easier to write and will introduce fewer trajectories in your result-file (good unless you want to debug what happens inside the function call I guess).

MatLab compiler auxiliary variables

I was wondering, does the MatLab compiler automatically change several calls to a function on the same object to one call ?
i. e.
someVector=zeros(length(someOtherVector),1);
for i=1:length(someOtherVector)
...
end
"Optimized"
aSize=length(someOtherVector);
someVector=zeros(aSize,1);
for i=1:aSize
...
end
By-question: How is this optimization technique formally called ? I understand, for instance, the JVM does this kind of stuff.
The MATLAB JIT Compiler makes plenty of optimizations, but I'm pretty sure it doesn't do the optimization you're suggesting.
To see why, imagine that you'd written your own function called length which returned a random integer whatever its input, and put it on the path so that it shadowed the built-in length. Then your second version would not only not be an optimized version of the first, it would actually have different effects.
Indeed, if you really wanted to mess around, you could implement length so that it wrote a new file called length and put that ahead of itself on the path, so that it would have entirely different effects the next time around.
MATLAB is quite a flexible language, which has a lot of advantages, but that makes it less possible to perform the sort of static analysis on MATLAB code that these sort of JIT optimizations would require. Java is much easier to statically analyse, so the JVM can perform more optimizations.

Change default numeric type to float in matlab

Matlab by default uses double as the numeric type. I am training a GMM and running out of memory, so I want to change the default numeric type to float which takes half the memory as double. Is it possible?
I know that single(A) converts a double precision element A to single precision but we need to allocate double precision storage for A first which runs out of memory. Also, I cannot use single() around all my matrix allocation as various functions in many toolboxes are called which I cannot change manually.
So is there a way that calling zeros(n) will allocate a matrix of floats by default instead of double ?
No, there is currently no way to change the default numeric type to float / single. See these informative posts on MathWorks forums:
http://www.mathworks.com/matlabcentral/answers/8727-single-precision-by-default-lots-of-auxiliary-variables-to-cast
http://www.mathworks.com/matlabcentral/answers/9591-is-there-a-way-to-change-matlab-defaults-so-that-all-workspace-floating-point-values-to-be-stored-i
Also, quoting John D'Errico on the first link I referenced - a formidable and legendary MATLAB expert:
This is not possible in MATLAB. Anyway, it is rarely a good idea to work in single. It is actually slower in many cases anyway. The memory saved is hardly worth it compared to the risk of the loss in precision. If you absolutely must, use single on only the largest arrays.
As such, you should probably consider reformulating your algorithm if you are using so much memory. If you are solving linear systems that are quite large and there are many zero coefficients, consider using sparse to reduce your memory requirements.
Besides which, doing this would be dangerous because there may be functions in other toolboxes that rely on the fact that double type allocation of matrices is assumed and spontaneously changing these to single may have unintended consequences.
As #rayryeng said, there's no way in MATLAB to "change the default numeric type" to single. I'm not even entirely sure what that would mean.
However, you asked a specific question as well:
So is there a way that calling zeros(n) will allocate a matrix of floats by default instead of double?
Yes - you can use zeros(n, 'single'). That will give you an array of zeros of type single. zeros(n) is just a shorthand for zeros(n, 'double'), and you can ask for any other numeric type you want as well, such as uint8 or int64. The other array creation functions such as ones, rand, randn, NaN, inf, and eye support similar syntaxes.
Note that operations carried out on arrays of single type may not always return outputs of type single (so you may need to subsequently cast them to single), and they may use intermediate arrays that are not of type single (so you may not always get all the memory advantages you might hope for). For example, many functions in Image Processing Toolbox will accept inputs of type single, but will then internally convert to double in order to carry out the operations. The functions from Statistics Toolbox to fit GM models do appear to accept inputs of type single, but I don't know what they do internally.

Matlab parametric plotting gui - vary parameters via sliders

I often have function such as:
sin(a*w*t + p)
where:
w = natural frequency
t = time
a,p = parameters (which I can vary)
As you can see if you want to vary a,p, you can do so via the standard interface but it's not very convenient. So I thought I'd look for a GUI which has a slider for each parameter. Does such a thing exist?
I've never seen one so I thought I'd quickly write one. However, I'm worried that due to lack of time and knowledge of matlab I will cause problems such as generating too many plot commands when the slider is moved instead of just one. Of course I also have the problem that I want to specify a field where the user can specify the function e.g. by typing sin(a*w*t +p) in a text field and then specify what each variable means which I currently don't know how to do (it looks like a parsing task). Can I do this or should I go with a predefined set of functions?
You can find similar projects in Matlab File Exchange as example.
For instance:
Integral Tool
Function Parameter Slider
I didn't have a look at the code but according to the screenshots, it should help you.
Regarding the function input feature, you can use the function eval (with a few checks on the input if you need reliability). If you want to allow any parametric variable, it may be harder.

How to modify an array in function?

MATLAB is a pass by value language. I have a recursive function that processes pixel's neighbors. It is very expensive to make the copy of the image (in my case two images) each time the function is called.
I used global variables to solve the problem. Is there any other way to make a recursive function modify an array?
You have three options here, but maybe you don't need any of them, since Matlab used 'copy-on-write', i.e. variables are only copied if you modify them.
As #gnovice mentions, you can use a nested function. Variables used inside the nested function are shared between the nested function and the enclosing function. Nested functions are somewhat tricky to debug, and a bit more complicated to write/understand.
You can store your images as properties of a handle object, which is passed by reference.
You can write code differently in order to not use a recursive function, since Matlab isn't the best language for using those. If you have access to the image processing toolbox, you may be able to use functions like blockproc, or im2col to rewrite the function.
Finally, if you want to stay with your current scheme, I strongly suggest using persistent variables instead of globals.
MATLAB is not always pass-by-value, newer versions of MATLAB do pass-by-reference under some circumstances, see in-place operations and a more general discussion about MATLAB memory management in this SO post.
Without tail-call optimization it is inefficient to use recursion and MATLAB does not have it as far I know, but every recursion can be transformed into a loop.
If you make your recursive function a nested function within another function where the image data is stored, then the recursive function can modify the image data without needing to have it passed to it.
This is a common misconception. Although the sytanx of MATLAB is pass by value, it does not actually pass by value as in C. The interpreter is smart enough to only make copies when necessary. So you should just go ahead and pass by value and see if you run into memory problems.
As other posters have noted, you should try to avoid recursion in MATLAB anyway.