DEV Community

dinhanhx
dinhanhx

Posted on

3 3

How stupid is Matlab function?

Function definition in a script

Python

Filename: the_amazing_file.py

def returnTrue():
    return True

print(returnTrue())
Enter fullscreen mode Exit fullscreen mode

Here you define the function first, then call it. It's like how you do math with paper. You write down the formula, then you apply it.

Matlab

Matlab motto

So the language for math, the function should be defined first right?

Yeah no.

Filename: the_amazing_file.m

disp(returnTrue());

function y = returnTrue()
    y = true;
end
Enter fullscreen mode Exit fullscreen mode

Seriously matlab, are you for math?

Calling non-parameter function

Let say you have a function foo() which doesn't have parameters

bar = foo() 
bar = foo
% Both are equivalent. 
Enter fullscreen mode Exit fullscreen mode

But foo() and foo mean two different things. foo() means calling a function. foo means "I'm a variable". If you use Python, it's passing functions as an argument. If you use C, it's function pointer.

Passing functions as argument vs Defining anonymous functions

Alright how to pass function as an argument in matlab? You use @ I copied this example from matlab function doc

% Compute the value of the integrand at 2*pi/3.
x = 2*pi/3;
y = myIntegrand(x)

% Compute the area under the curve from 0 to pi.
xmin = 0;
xmax = pi;
f = @myIntegrand;
a = integral(f,xmin,xmax)

function y = myIntegrand(x)
    y = sin(x).^3;
end
Enter fullscreen mode Exit fullscreen mode

Guess what else use @? Anonymous functions

sqr = @(x) x.^2;
Enter fullscreen mode Exit fullscreen mode

If you look at the way anonymous function is defined and look at how non-parameter function (previous section), you may ask the following line

bar = foo;
Enter fullscreen mode Exit fullscreen mode

could mean anything right? Yeah it could mean:

  • calling a function without parameters
  • assigning anonymous function to different variable.

The more confusing, the more we analyse.

Now you may argue, "I know my functions". Yeah but can you remember other people functions when reading a long file while trying to understand what it does? Can you?

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more