MATLAB has many uses, but the most basic, and the first thing to master when starting out, is the use of the MATLAB Command Window.
The MATLAB Command Window is one of the main tools for entering data, running MATLAB functions and scripts, and displaying results. By default, the MATLAB Command Window is located in the middle of the MATLAB Desktop interface. Additionally, the Command Window can not only be embedded in the MATLAB Desktop interface, but by clicking the button on the Command Window, it can also be made to float, as shown in Figure 1-12. If you wish to re-embed the Command Window into the MATLAB interface, you can click the button and select the command.
The “>>” in the Command Window is the prompt, indicating that MATLAB is in a ready state. After entering a command following the prompt and pressing the Enter key, MATLAB will provide the calculation results or corresponding error/warning messages, and then enter the ready state again. When MATLAB displays the prompt “K>>” in the Command Window, it indicates that it is currently in debug mode; typing “dbquit” returns it to normal mode. In the MATLAB Student Version, the prompt displayed is “EDU>>”.
1. Using the Command Line
You can enter data or run functions after the command prompt.
[Example 1] Data input example.
>> A = [1 2 3; 4 5 6; 7 8 10]
After entering the 3*3 matrix A and pressing the Enter key, the corresponding command will run, completing the data input, resulting in:
A =
1 2 3
4 5 6
7 8 10
It should be noted that MATLAB is case-sensitive. For example, in this case, the matrix is assigned to the variable A, not the variable a.
Additionally, in MATLAB 2014b, users can copy commands from other places (web pages or electronic documents) and paste them into the command line to run. This is achievable in other languages as well, but MATLAB clearly does it better; it humanizes the process by automatically removing the command prompt from the beginning of each line in multi-line commands (the command prompt must have a space for recognition), allowing users to run without having to copy each line carefully and avoid the command prompt. This makes it much easier for users to verify results while reading other electronic materials.
[Example 2] Arithmetic operation example. Calculate the result of the expression 29*(2+23/3)-52.
Enter the following command in the command line and press Enter to get the corresponding result.
>> 29*(2+23/3)-5^2
ans =
255.3333
Since the user did not specify a variable name for the return value, MATLAB returns the result to the default variable name ans.
If you want to run a built-in or user-defined function, that function must be in the current directory or in MATLAB’s search path. By default, built-in functions are in the search path, and readers can run them directly. Input the function and its variables and press Enter, and MATLAB will display the corresponding results.
[Example 3] Example of running the MATLAB magic function.
>> magic(3)
ans =
8 1 6
3 5 7
4 9 2
In this example, magic is a built-in function of MATLAB. The magic function can generate a magic square matrix where the sum of each row and column is equal. The input magic(3) specifies the number of rows in the generated magic square matrix.
In MATLAB, only one command sequence can be executed at a time. If MATLAB is running a function, any input function will be queued and will only run after the previous command has finished. Sometimes a program may run for a long time; if readers want to interrupt the program due to discovering an error or for other reasons, they can use the Ctrl+C shortcut.
In MATLAB, the command line will check for incorrect syntax and provide possible correct expressions. For example, if you input
>> magic(3
and run it, the command line will give an error message and automatically suggest the correct expression.
magic(3
|
Error: Expression or statement is incorrect–possibly unbalanced (, {, or [.
Did you mean:
>> magic(3)
At this point, the user can simply press Enter to get the correct result. Currently, the automatic correction of syntax includes missing parentheses ), ], and }, assignment operators ++, +=, and -=, mathematical expressions 2(x+1), function name case errors, etc. This feature is particularly convenient for users, especially beginners.
2. Values, Variables, and Expressions
The previous examples are just the simplest arithmetic operations and function executions in MATLAB. Before further learning, it is necessary to understand some basic rules of MATLAB. This section introduces several rules regarding variables.
1. Representation of Values
MATLAB uses the conventional decimal representation for values, which can include decimal points or negative signs. The following representations are all valid.
4 -29 0.114 84.249 1.349e-4 6.3e13
On computers using the IEEE floating-point algorithm, the relative precision of values is eps (= 2.2204e-16), which approximately maintains 16 significant digits. The range of values is roughly 10e-308 to 10e308, i.e., 1×10-309 to 1×10309.
2. Variable Naming Rules
In MATLAB, variables can be assigned without prior declaration. Variable names and function names are case-sensitive. For example, the variable FU and the variable fu represent two different variables. sin is the sine function defined in MATLAB, while SIN and Sin are not. When inputting SIN, the system will prompt an error and then provide a suggestion:
>> SIN(3)
Undefined function ‘SIN’ for input arguments of type ‘double’.
Did you mean:
>> sin(3)
In MATLAB, the first character of a variable name must be an English letter. Variable names can contain up to 63 characters. However, for the sake of program readability and convenience, variable names should not be too long.
Built-in variable names in MATLAB generally conform to this naming rule, and their names are not too long but also not so short that their function is unclear from the name. Naming conventions often use abbreviations of English words, making it generally intuitive to understand the function from the name.
Variable names cannot contain spaces or punctuation, but they can include underscores, such as myvar_ga.
3. MATLAB’s Default Predefined Variables
In MATLAB, there are some so-called predefined variables. These variables are generated every time MATLAB starts. It is recommended that readers avoid reassigning the variable names listed in Table 1-1 when writing programs to prevent confusion and incorrect calculation results.
Table 1-1 Predefined Variables in MATLAB
Predefined Variable |
Meaning |
Predefined Variable |
Meaning |
ans |
Default variable name for calculation results |
NaN or nan |
Not a number, e.g., 0/0, ¥/¥ |
eps |
Floating-point relative precision |
nargin |
Number of input variables for a function |
Continued Table
Predefined Variable |
Meaning |
Predefined Variable |
Meaning |
Inf or inf |
Infinity |
nargout |
Number of output variables for a function |
i or j |
Imaginary unit i=j= |
realmax |
Maximum positive real number 1.7977e+308 |
pi |
Pi π |
realmin |
Minimum positive real number 2.2251e-308 |
4. Complex Numbers
MATLAB treats complex numbers as a whole, without needing to separate the real and imaginary parts as in other programming languages. The imaginary unit is represented by the predefined variables i or j.
[Example 4] Input of complex numbers and related function examples.
>> sd=5+6i
sd =
5.0000 +6.0000i
>> r=real(sd) % Gives the real part of the complex number sd.
r =
5
>> im=imag(sd) % Gives the imaginary part of the complex number sd.
im =
6
>> a=abs(sd) % Gives the modulus of the complex number sd.
a =
7.8102
>> an=angle(sd) % Gives the phase angle of the complex number sd in radians.
an =
0.8761
In this example, the % following each command indicates a comment. MATLAB ignores the statements after the % when executing commands. This method of commenting is used to clarify the meaning of function statements for the reader while saving space.
[Example 5] Generation and operation of complex matrices.
>> A=[2,4;1,6]-[3,7;3,9]*i
A =
2.0000 -3.0000i 4.0000 – 7.0000i
1.0000 -3.0000i 6.0000 – 9.0000i
>> B=[2+5i,3+2i;6-9i,3-5i]
B =
2.0000 +5.0000i 3.0000 + 2.0000i
6.0000 -9.0000i 3.0000 – 5.0000i
>> C=B-A
C =
0 + 8.0000i -1.0000 + 9.0000i
5.0000 -6.0000i -3.0000 + 4.0000i
This example shows that complex matrices can be input in various forms. Readers can generate corresponding matrices according to the matrix construction methods introduced in later chapters.
[Example 6] Using MATLAB to calculate the cube root of -8.
>> a=-8; % Adding a semicolon at the end of the command line “;” means the result will only be stored in the workspace and not displayed in the command window.
>> r=a^(1/3) % Calculating the cube root of a.
r =
1.0000 +1.7321i
As can be seen, MATLAB gives the first quadrant root of -8 during the direct calculation, which is not the -2 we are familiar with. To obtain all the cube roots of -8, run the following commands.
>> m=[0,1,2]; % Setting for 3 cube roots
>> R=abs(a)^(1/3); % Calculating the modulus to the 3rd power
>> theta=(angle(a)+2*pi*m)/3; % -pi<theta<=pi for the 3 phase angles
>> r=R*exp(i*theta) % Assigning the obtained results to r
r =
1.0000 +1.7321i -2.0000 + 0.0000i 1.0000 – 1.7321i