When you add a folder to path, you often want to add all its subfolders (and their subfolders) to path too. In this case, you can use genpath. e.g.
- use ii, instead of i, in loop (suggested by Chess Stetson)
You probably use the following code a lot:
for i=1:100. The problem here is that i is special in MatLab. It stands for the imaginary number. So it’s a good idea to avoid it.
If you want to get some data from a webpage, you can use s = urlread(‘https://www.alivelearn.net’). Then you can parse the returned string s.
- split a string
You can use
parts = regexp(tline,'\t','split');to split a string into parts.
- Find common numbers (or strings) of two arrays (or cell arrays)
You can use intersect(A,B) to find common numbers or strings.
- Do not use guide for big projects
Guide is a quick way to build a graphic interface. But for bigger projects building the interface programmatically in the m file is more flexible. You have precise control of button positions, you can easily delete or add components and don’t worry about junk codes in your file. And you have only one file (the m file) instead of two files (fig file and m file).
- Try to avoid explicit loop.
If you can use matrix operation, use it instead of looping. For example, if you want to multiply two vectors element by element and get the sum, then use A*B’ instead of doing a loop. It is much faster.
- Allocate memory first for large arrays.
If you know that the size of an array is one million, then allocate memory first (A = zeros(1, 1000000)), then fill numbers to each element. If you don’t allocate memory first, MatLab will keep allocate memory dynamically and the performance will be slow.
In your base workspace there is a variable called ‘x’. How to get the value of x? You can use evalin(‘base’,’x’). Sometimes you may not explicitly know the variable’s name – you only know the variable’s name is stored in another variable called y, then you do evalin(‘base’, y).
If you want to make a larger matrix from a smaller one, you can use repmat. For example, B = repmat(‘this is a string’, 10, 1).
If you need to call system functions, you can use system. For example, system(‘dir’)
Small MatLab tips
1 min read