Mayank Lakhani
Mayank Lakhani

Reputation: 193

Overwrote built in function - Standard deviation

I want to have a std.m file for the standard deviation. It is in data fun toolbox, but, by mistake, I changed the code and the std command is not working anymore. How can I run the original std (standard deviation) command?

Upvotes: 4

Views: 165

Answers (1)

Hoki
Hoki

Reputation: 11802

Taking all the comments out, the function std.m is actually extremely simple:

function y = std(varargin)
    y = sqrt(var(varargin{:}));

This is the definition of the standard deviation: the square root of the Variance.


  • Set built-in functions to Read-Only

Now don't go breaking the var.m file because it is more complex and I wonder if there would be copyright issue to display the listing here.

To avoid the problem of breaking built-in files, it is advisable to set all your Matlab toolbox files as Read Only. I remember old Matlab installer giving the option to do that at install time. I don't know if the installer still offers the option, but if not it is extremely easy to do it manually (on Windows, just select your folders, right-click Properties, tick read only and accept to propagate the property to all subfolders and files).


  • Overloading

Once this is done, your built-in files are safe. You can still modify the default behavior of a built-in function by overloading it. This consist in writing a function with the same name and arrange for it to be called before the default function (your overload function becomes the default one).

This article explain how to overload user functions.

Matlab does not recommend to directly overload the built-in functions (rather call it another name like mySTD.m for example), but if you insist it is perfectly feasible and still a much better option than modifying the built-in function... at least the original function is still intact somewhere.

Upvotes: 6

Related Questions