MATLAB Answers

Experts of MATLAB, how did you learn? Any advice for beginner/intermediate users?

1.324 views (last 30 days)
bio lim
bio lim on 6 Jul 2015
Edited: Stephen on 16 Oct 2021 at 19:26
The community is very helpful, yet I feel really powerless that I cannot find the appropriate way to code, nor find the problems with the codes I have written. I have read numerous books on MATLAB, mostly related with science and engineering applications. Any advice to improve would be greatly appreciated. Thanks.
  5 Comments

Sign in to comment.

Accepted Answer

Stephen
Stephen on 6 Jul 2015
Edited: Stephen on 16 Oct 2021 at 19:26
I reject the label "expert", but here is my two cents worth anyway:
MATLAB Specific:
  • 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.
  • Learn about comma-separated lists, and the easy ways to use them.
  • 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.
Code Design:
General Advice:
  • 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.
See also:
  19 Comments

Sign in to comment.

More Answers (10)

Chad Greene
Chad Greene on 6 Jul 2015
I've learned a tremendous amount by asking and answering questions on this forum. I probably learn more when I answer questions than when I ask.
The one thing that really stepped up my skills, though, was developing a habit of properly documenting the codes I write. I typically spend twice as much time writing documentation as I do actually writing the functions, but I am convinced it's worth it. The benefits of good documentation are multifaceted:
  1. 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?"
  2. 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.
  3. 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.
I am convinced that the best way to become a good coder is to write good documentation. Teaching is the best way to learn, and writing good documentation is teaching. You don't learn many tricks when you write documentation, but you learn how to think about problems, and you develop an intuition for how to make code more efficient and more user friendly. The more user-friendly your codes are, the less cluttered the user's mind will be, the more you'll understand your own code, the more efficient your codes will be, and the more repeatable your science will be.
In my view, the best way to become a better Matlab coder is to learn and use the publish feature. Syntax, Description, Examples. For everything you ever write, even if it's only for yourself.
  3 Comments

Sign in to comment.


Walter Roberson
Walter Roberson on 6 Jul 2015
I have not read any books on MATLAB.
I mostly read a lot of postings in the MATLAB Usenet newsgroup, comp.soft-sys.matlab . It does not take long before questions pretty much repeat and one can start to answer other people based upon what one learned before. Through reading enough Questions and the answers from other people, and some experimentation, and reading documentation, one can learn a great deal.
My response has to be understood in the context that I was already a quite experienced programmer when I started using MATLAB, so MATLAB was "more of the same" with some interesting features added on. Possibilities such as classes and parallel programming are, to an experienced programmer, less about syntax and more about learning new ways of thinking about programming. (But experienced programmers can get a bit fossilized in how they think about programming, so it can take a lot of practice to learn completely new ways. I never really "got" object-oriented programming, for example.)
  2 Comments

Sign in to comment.


John D'Errico
John D'Errico on 6 Jul 2015
Like Walter, I learned to program in older languages - mainly Fortran & APL. This teaches you good concepts about programming, but languages like Fortran can be counterproductive if they get you in the habit of writing loops. I imagine that C is also in that bin, though I cannot tell, since I can barely spell C, not to mention write in it. (Newer versions of Fortran allow array operations, a much easier way to write code, and better for moving to MATLAB.)
The point is though, that you may need to learn a new programming style, thinking in terms of operations on entire arrays, rather than single element operations wrapped in loops. This takes some practice.
To learn MATLAB, I'd suggest picking a problem that interests you, and solve it. You might start with the Cody problems, but I'd suggest harder and more interesting problems like the Project Euler problems. Many of them are quite solvable in MATLAB. (I've done a few hundred myself in MATLAB, so I know this to be true.)
As you advance in skill, you can also try picking apart the code of others, as found on the File Exchange. I've got 50+ tools on the FEX for example. Pick a simple one, and look how I wrote it. This can teach you things about various programming styles, especially if you look at the work of other respected authors on the FEX.
And of course, you can learn a lot by reading the forums. Be careful though. Apply a filter to what you see, since anyone can answer a question. (Including me!) Think about what you see, and decide if it makes sense to you.
  1 Comment
bio lim
bio lim on 6 Jul 2015
Thanks for the great advice! I have also taken Fortran in some of my engineering classes, but was not very interested in programming that time. However now, after started learning MATLAB, I can see how amazing it is. Never thought programming would be this exciting!

Sign in to comment.


Adam
Adam on 3 Mar 2016
Edited: Adam on 3 Mar 2016
I hadn't noticed this question at the time (or I think maybe I did, but Stephen's answer was so comprehensive as regards advice that I didn't feel the need to add anything).
To give an answer on a more personal note though, I have first started working in Matlab ~9 years ago. At the time I was a novice C++ programmer, fairly fresh out of a Computer Science PhD, had been offered a job as a software engineer, but mostly with the intention of me becoming the 'research engineer' that I am now - i.e. I do some research, come up with lots if ideas, implement them as prototypes and hopefully they are good enough for our company to put into our main software. I'm neither an expert software engineer nor an expert researcher, I'm just quite good at combining the two in a useful manner.
Matlab was the tool that I was given to do most of this research in, though for many years I did so alongside also programming in C++ for long periods. When I started I had never even heard of Matlab. To this day I have never been on a single Matlab course or done any kind of official training, I have just learned on the job and continue to do so.
Right now I would say I am more of a 2nd tier expert if we accept that people like Stephen, Walter, Chad, John D'Errico are top tier experts. I have a good depth of knowledge in the areas I have used and am able to provide help and advice on those, but I still learn a huge amount from people like those named and others at the same time through browsing this forum.
As I began to produce prototype demos I made it a mission to try to learn at least one new thing in Matlab with every new prototype I created and always enjoy the software engineering design aspect in a language like Matlab. After many years of working in GUIs we began to start building ever more complex tools with multiple communicating windows, etc. At this point I decided it was time to learn Matlab OOP which was pleasingly easy. I completed a 2 week project using OOP for the first time in less time than my boss had expected it to take without knowing I was learning a whole new way of programming. It was one of the best Matlab decisions I have made. Now > 95% of the code I write is object-orientated and I believe our code base is vastly better for having taken that leap.
As for other stuff though, in addition to learning as I go through experimentation and the excellent documentation I started visiting this forum. From the outset I decided I wanted to give at least as much as I 'take' so I began answering questions before I asked my first. I found that I actually have a lot of knowledge that can be passed on to others and by doing so, as others said, I learn a huge amount. That is important because I am doing a full time job - whilst helping others is nice I only spend work time doing so because I learn a lot that improves my own programming too so my employers gain from that.
In addition to this forum Yair Altman's blog has regularly been a source of enlightenment for me, especially when I go 'off-piste' with my requirements and need to delve into java.
Finally, two of the biggest things that helped me learn Matlab:
  • 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.
  2 Comments
John D'Errico
John D'Errico on 30 Mar 2017
Walter makes a good point. I've written up my thinking on hundreds of hands of bridge that I have played. Not MATLAB, but often just as difficult. What I found was that by writing out my thoughts in a clear, cohesive manner so that others can follow them, it forced me to actively think about the problem. It made concepts clear to me that otherwise were slightly fuzzy.

Sign in to comment.


DGM
DGM on 6 Jul 2021
Edited: DGM on 6 Jul 2021
Everyone else here has covered what are arguably the more useful answers. I'm no expert, but I think one point that hasn't been mentioned (similar to Stephen's last point) was to spend some time to casually become familiar with your tools without the burden of performing a task for others.
I was taught to type on a typewriter and came away from all that practice without any practical typing ability. It wasn't until I was motivated to communicate with others in real time online that I learned to type for my own selfish motivations. Likewise, all the coursework and research I pushed through Matlab hardly taught me much in terms of breadth or depth of familiarity. It wasn't until I started writing my own projects that the challenges felt meaningfully rewarding and I began to find some shreds of confidence.
... maybe I just outed myself as a terrible learner. I guess I'm old enough to live with that.

Steven Lord
Steven Lord on 1 May 2020
Edited: Steven Lord on 1 May 2020
Two questions that can be useful to ask when writing a significant piece of code are "What problem am I trying to solve?" and "What steps do I need to do to solve my problem?"
Sometimes when I'm writing code I'll start off with either just a bunch of comments listing the steps or a series of function calls (no bodies yet, just the names.) This is just to fix the series of steps in my mind and ensure that I'm not missing anything. Once I have the general workflow in place, I determine what each of those steps needs to receive as input and what it needs to produce for other parts of the workflow. This finishes the signature of each of my functions. Then I can implement each step as its own function, independent of the rest of the workflow. This limits how often I have to go back to an already-implemented function and change it to satisfy the requirements of later functions.
You may be tempted to save time by using short, potentially cryptic function or variable names. I recommend resisting that temptation unless maybe the variable is only in use for a very short period of time. So using single letter variable names like t and y as the input arguments of an anonymous function may be okay.
odefun = @(t, y) t.*y;
For anything that's going to be used repeatedly, I try to choose function and variable names that make my code look more or less like English sentences or phrases that describe the purpose of the function, the variable, and/or the function call. Tab completion can help limit how much typing you need to do. Consider one example:
data = readDataFromFile(filename);
Without knowing anything about the body of that function, you can get a pretty good sense of what it does and roughly what it returns.
data = readDataFromFile(filename);
cleanedData = removeOutliersAndMissing(data);
Those seem like two reasonable steps in the process of analyzing data from a file.
The debugging tools, Code Analyzer, and other tools to help you fix and avoid problems in your code have already been mentioned and they're good tools to have in your toolbox. There are a few others that may have been mentioned in passing that would be useful particularly for larger projects.
  • 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.
  1 Comment
Walter Roberson
Walter Roberson on 18 Nov 2020
odefun = @(t, y) t.*y;
The variable names may be short and cryptic there, but in the context of ode numeric solvers they are also conventional, and that can help a fair bit in having them recognized. Just like how all of the Mathworks optimizers use names such as A, b, Aeq, beq, lb, ub: the coding pattern can become strong enough with common repetition that using different names can start to be distracting.
(If you dig into the implementation of ode45 then you will find a lot of places where you are asking yourself what the difference is between input parameter names and names carried around through the code, because there is a programming maxim that if you use a different name then it should be for a different purpose.)

Sign in to comment.


Javier
Javier on 16 Sep 2021
Edited: Javier on 16 Sep 2021
Hello, I am not a Matlab expert by no means. I have been using Matlab for about two years.
Something that has really helped me is to look for other things that I can use Matlab for, that can make my workflow more efficient.
For example, when I am working on a .tex document (which is very used in engineering at my university), instead of making the table yourself, which could take a lot of time, look for a function that can make it for you.
Also, try to use them for personal proyects (to manage different format files), or proyects that are not necesarily engineering ones.
Reading some books and looking at courses if you are starting out is also something useful.
Also, try to ask and answer questions on the Matlab Answers forum, you could really learn from studying diferent solutions to other people's questions, and then trying to solve such question in your own way. There may be some difficult ones but there are also some challenging enough ones.
Also, if you understand the errors that appear on your command window, I think coding will be so much easier.

Brett Pantalone
Brett Pantalone on 28 Jan 2021
It takes a little time to get proficient in MATLAB, especially if you are coming from more traditional programming languages. I agree with everything said in the previous answers, but I'd like to emphasize a few of the things that really helped me personally.
  • 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.
Good luck!
  1 Comment
Walter Roberson
Walter Roberson on 28 Jan 2021
Vectorization is not always best. In some cases it can force you into multi-dimensional logical arrays, calculate the values over the whole range of possibilities as-if all the entries were going to be selected, and then selecting the answers using logical mask. As the dimensionality goes up, the fractional of entries that are eventually going to be selected can go down quickly, and it can become much faster to instead loop and select only limited subsets to calculate over.

Sign in to comment.


Kerem Utku Demir
Kerem Utku Demir on 5 Jul 2021
Self-paced courses are enough.
  2 Comments
Cutie
Cutie on 6 Jul 2021
@Walter Roberson, you are right. The self-paced course aren't enough until one start 'getting his/her hands dirty' with practical implementation before you can know 'how much you know!'. I have particulary found this community helpful.

Sign in to comment.


Sulaymon Eshkabilov
Sulaymon Eshkabilov on 6 Jul 2021
Really great points on practical and theoretical aspects how to study and master programming in MATLAB environment. My learnig experience of MATLAB and Simulink was a little bit different from the points highlighted above. During my college years, I have employed MS Excel and Visual Basic programming in MS Excel in most of engineering and numerical analysis classes. Then I challenged myself to do everything what I had done in MS Excell and Visual Basic programming in MATLAB.
Later, I challenged my research fellow colleagues to perform all simulation and modelling problems of ours in MATLAB and Simulink environments and find out differences in solutions if there are any. These challenges were really fun and sometimes frustration due to simple ("now we call") or silly mistakes such as overlooking a solver type (i.e. fixed-step solver vs. variable-step solver) or error tolerance ('RelTol', "AbsTol") or executing Simulink models with undefined variables in the MATLAB workspace. One nugget here for Simulink modelling people how to carry all variables and their values along with the models is to define all variables and their values in: Model Explorer -> Callbacks -> InitFcn
As pinpointed above by others, "practice makes perfect!".
One great lifetime lesson that my Math Teacher in school taught was to solve any given problem with at least two or more different ways. That practice I have applied in solving various problems in MATLAB and Simulink in parallel that also helped me to study many different features of programming in MATLAB and Simulink.
Another practice of mine that I have found very essential in learning MATLAB/Simulink is designing and solving specific engineering projects in vibrations, control problems of dynamics, image analysis, etc.
Last but not least by helping others to solve their problems and teach others one can gain significant amount of valuable experiences including new features of MATLAB/Simulink packages and their toolboxes.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by