Experts of MATLAB, how did you learn? Any advice for beginner/intermediate users?
66 Comments
Time DescendingPractice makes perfect
Hi,
I have a collection of samples programs posted on my MathWorks page on here. I also have a collection of YouTube videos that I've put together to help people through basics and some complicated things in MATLAB. These videos correspond to step by step directions on how to make the programs I've posted on MathWorks. How to Create Programs in MATLAB (tutorial): YouTube MATLAB tutorial
I also reply to any comments on YouTube to answer MATLAB questions. I'm always happy to help out.
Best of luck on your learning journey. -Kelsey
- use modulatization, such as functions for repeating tasks in code
- debug small parts of your code before getting huge
- use in appropriate steps output including text and figure and maybe files
- let your code be reviewed by colleagues
- and my favourite one: distrust yourself, you might have been wrong in coding, double check.
- Understand how MATLAB uses vectors and matrices, and the various ways you can access them using subscripts and slices. Learn how to use a logical mask to filter elements of a vector or matrix.
- Learn to vectorize operations. When you find yourself writing a FOR loop, try to eliminate it using a vector operation. Usually you can do it, making your code faster and easier to understand.
- MATLAB's help system is one of the best. Use 'help <command>' to be reminded of command syntax, and 'doc <command>' to read about usage details and optional parameters.
- Don't reinvent the wheel. MATLAB includes lots of built-in functions that can deal with many types of problems, not to mention all of the specialized toolboxes.
- Don't try to write perfect code the first time. Get something working, verify your results, and then optimize it for size or speed if needed.
- Use comments liberally to document your code. Even if something seems obvious today, after some time has passed you may find yourself wondering, "What the heck was I trying to do here?" Writing good comments saves time in the long run.
- Break problems up into smaller pieces, and write functions instead of large scripts. This helps improve code architecture and makes it easier to reuse, debug, and share code.
- Looking at other people's code helps with learning and understanding MATLAB's unique programming idioms and best practices. Check the file share section for solutions to specific problems.
- Finally, the MathWorks question and answer forums have lots of helpful information. But you already knew that.
- the Profiler can help you understand where the performance bottlenecks in your code are located, focusing your attention on the long poles.
- Given the department I work in at MathWorks, I don't think it'll surprise anyone that I give a plug for the testing tools. Even a few script-based tests to lock down the behavior of the most critical part of your code will help you when or if you need to change that code, to reduce the chances that you'll break it. Note that we have frameworks both for correctness of your code and to measure performance, to reduce the chances that you'll slow your code down and not notice.
- The Matlab Command Window - use it! Experiment with syntax and try things out because it is easy
- The debugger - allied with the Command Window debugging code and being able to play around on command line from within a debug session is invaluable.
- I always start with a Syntax section. This is where I have to ask myself, "how will users try to use this function?" and "what are the simplest, most intuitive options the function can have?"
- Next comes a Description section. This is where I describe the different options listed in the Syntax section. This step forces me to think about what exactly the function is doing and why.
- The Example section is the big opportunity for learning. The process of writing a good set of examples serves quadruple duty as you'll think of all the ways your function can be used, you'll think of new options that your function should have, and you'll see the ways your function could be more user friendly. If you make examples to highlight every different way your function can be used, running those simple examples will be a great way to error check your code.
- MATLAB has a great feature that very few programming languages have: readable documentation. Use it! Search it using your favorite internet search engine. Practice browsing it via the contents on the left-hand side (which are all hyperlinks). Understand how it is grouped by topic. Try out the examples. Use the help to locate related functions and advice on how to solve particular problems.
- Note that the online documentation is for the current MATLAB release: your installed MATLAB version may be different, so ultimately you should always refer to the installed help of your installed MATLAB version.
- Read the help for every function and operation that you use, no matter how trivial you think that operation is. Half of the questions that we answer on this forum are solved by reading the documentation for the function/operator that the user is already using!
- Learn to use the debugging tools. These are indispensable. Read about how they work and what they do, then practice using them! For starting debugging, the most useful command is: dbstop if error
- Learn the differences between array and matrix operations, otherwise your calculations will simply produce nonsense and you won't know why. If you are not doing linear algebra you probably need array operations (aka element-wise operations).
- Learn about comma-separated lists, and the easy ways to use them.
- Learn about indexing, which is one of MATLAB's superpowers. In many cases logical indexing is the simplest and most efficient (but all of the different ways of indexing are useful in different situations).
- Pay attention to all of the code warnings, error messages, underlining, and tips that the MATLAB Editor shows. Do not ignore these messages.
- Learn good MATLAB programing habits right from the start, because life is too short to un-learn bad habits! This means: comment your code, use consistent formatting, write help (with H1 line) in every function, pass variables properly, use input checking, never use eval (or assignin, feval, etc), etc.
- MATLAB blogs are an excellent source of inspiration and ideas. Loren Shure's blog is a mine of great ideas, and a veritable pleasure to read too.
- Check out other people's code on File Exchange (FEX). Note that the comments are often more useful than the ratings... and you will soon get an idea of whose comments are particularly worth paying attention to.
- Write functions, not scripts. Scripts are good for playing around with, but not for real work.
- Make vectorized code your first choice when writing code, and leave those ugly low-level loops behind you... Understand why vectorized code is beautiful, and how it can be used to make your code much more efficient and easier to understand.
- And of course when loops are required, always preallocate the arrays before the loops
- There are important ways to write fast and efficient code. Use them.
- For example, instead of slow and hard-to-debug cd (or even worse, adding data folders to the MATLAB search path) use absolute or relative filepaths when importing/exporting file data.
- In filepaths, use '.' to refer to the current directory (rather than slower pwd or cd).
- In filepaths, use '..' to refer to the parent of a folder.
- Do not use if to operate on parts of your vector/matrix, most likely you should be using logical indexing.
- Pass variables reliably using input/output arguments and do not use globals or assignin. If you need to pass lots of values (e.g. simulation parameters) then put them into a structure and pass that.
- Refer to all graphics objects (figures, axes, lines, etc) using explicit handle references (e.g. using Parent property). This makes plotting and handling graphics robust and predictable. Do not assume that the current figure/axes/etc is going to be the one that your code needs to access.
- Do not force meta-data (e.g. dates, times, indices, test parameters, etc) into variable names or fieldnames: meta-data is data, so store it as data in an array.
- Use subs to substitute values into a symbolic expression and evaluate it. Do not use eval to do this, it is not the correct tool for the job!
- Imagine that every script and function you write is going to be given to someone else... impress them!
- Test everything thoroughly. Check each line as you write it. Does it really do what you think it is doing? Many beginners come here to ask for help because they only think about what they want their code to be doing, but never bother to actually check what their code really is doing. Code cannot read your mind.
- Make a set of test-cases and collect all of the instances that fail while the code is being written, plus all the edge-cases and every case category that it needs to work with. You will not regret doing this.
- Break problems into parts, solve the parts separately. Make functions for code that needs to be repeated: this allows code to be reused, and bug-fixed in one location. Scripts are great for quickly testing an idea, but functions are much more robust for anything that will be used for more than one day.
- Think about what you are doing: actually think. What is the problem being solved? What is really the problem? How can it be solved? With what methods? Read Pólya's excellent book How To Solve It.
- Don't get stuck believing that you have found the best solution... there can be a much better solution waiting just around the corner, that may just require a new perspective, a reformulation of the problem, or a slight rearrangement of the data. Keep an open mind.
- Practice! Challenge yourself with tasks you want to solve, or take part in onlne code challenges or tutorials.