DEV Community

Cover image for Handy MATLAB Tips for beginners: Syntax, variable names and more
Sandra
Sandra

Posted on • Originally published at sandramartin.hashnode.dev

Handy MATLAB Tips for beginners: Syntax, variable names and more

In this super little post, I will give some tips that, I hope, will benefit beginner MATLAB users. They will be related to syntax and variable names. So, let's go!

Tip 1: Spaces

Generally, spaces do not affect MATLAB code when creating variables (except when creating arrays), so you can decide whether you want to put them or not.

I recommend using them as they make the code easier to learn. For example, MATLAB will interpret these two lines equally, independently of the spaces:

x=3;
x = 3;

Enter fullscreen mode Exit fullscreen mode

One thing to consider when using spaces is that you can't add them in variable names. Those names may have digits and letters, but never white spaces.

For example, you can have a variable called myVariable or my_variable, but not my variable because it includes spaces in it.

Tip 2: Syntax Errors

When we commit an error in MATLAB, it lets us know with some red lines that describe the said error. For example:

MATLAB error.png

In the example above, I have committed a syntax error, as I can't assign a value to a constant, and MATLAB informs me about that.

We describe a syntax error as not fulfilling the proper form of a MATLAB statement. And this term applies to any programming language, not only MATLAB.

Tip 3: Variable names

A variable name can be a letter or a word. We can use numbers (they can't be the first element of the variable name) and lower case and upper case letters.

We can check the highest number of characters allowed for a variable name in MATLAB with the namelengthmax command. If we write an identifier longer than the maximum, then MATLAB will ignore the extra characters.

MATLAB also differentiates between upper and lower case. For example, a variable called M is different from another one called m. Or a variable called CAR is different from cAr.

We can also include underscoring in our variable names (but we can't use them as the first element). For example, we can have a variable called my_car.

To sum up

In this short post, I've written the three most common mistakes beginners make when they begin programming, and I hope to have given some handy tips on how to address them.

The most important thing to correct our mistakes when programming (as no matter how good we are, we will always make mistakes) is to read what the error is, so we can begin correcting it.

Useful links

Check other articles in my MATLAB series if you want to know more!

Top comments (0)