Matlab入门
-
Commands
Enter commands in MATLAB to perform calculations and create variables.
Enter commands
You can execute commands by entering them in the command window after the MATLAB prompt (>>) and pressing the Enter key.
3*5
Unless otherwise specified, MATLAB stores calculations in a variable named ans.
>> 7+3 ans = 10 >> m = 3*5 m = 15
The equals sign (=) in MATLAB is similar to the equals sign in C, So when you enter
x=3+4
, MATLAB first evaluates3+4
and the assigns the result (7
) to the variablex
.That the Workspace window shows all the variables currently in the workspace.
Adding a semicolon(
;
) to the end of a command will suppress the output, though the command will still be executed, as you can see in the Workspace. When you enter a command without a semicolon at the end, MATLAB displays the result in the command window.>> x = 5 + 1; >>
You can recall previous commands by pressing the Up arrow key on your keyboard. Note that the Command Window must be the active window for this to work.
When you enter just a variable name at the command prompt, MATLAB returns the current value of that variable.
Storing Data in Variables
You can name your MATLAB variables anything you'd like as long as they start with a letter and contain only letters, numbers, and underscores (_).
Try clearing all variables by entering the command
clear
.clear
removes workspace variables, andclc
clears the Command Window.Using Built-in Functions and Constants
MATLAB contains built-in constants, such as
pi
to represent. >> a = pi a = 3.1416
Also, although only four decimal places are shown for
, it is represented internally with greater precision. MATLAB contains a wide variety of built-in functions, such as
abs
(absolute value) andeig
(calculate eigenvalues).>> a = sin(-5) a = 0.9589
Note that MATLAB uses parentheses to pass inputs to functions, similar to standard mathematical notation.
>> z = sqrt(-9) z = 0.0000 + 3.0000i
Note that the solution contains the imaginary number,
i
which is a built-in constant in MATLAB.Vectors and Matrices
Create MATLAB variables that contain multiple elements.
Manually Entering Arrays
All MATLAB variables are arrays, meaning that each variable can contain multiple elements. A single number, called a scalar, is actually a 1-by-1 array, meaning it contains 1 row and 1 column.
You can create arrays with multiple elements using square brackets
[]
.>> x = [3 5] x = 3 5
When you separate numbers by spaces (or commas), MATLAB combines the numbers into a row vector, which is an array with one row and multiple columns (1-by-n). When you separate them by semicolons, MATLAB creates a column vector (n-by-1)
>> x = [1;3] x = 1 3
You can combine spaces and semicolons to create matrices, which are arrays with multiple rows and columns. When entering matrices, you must enter them row by row.
>> x = [3 4 5;6 7 8] x = 3 4 5 6 7 8
In MATLAB, you can perform calculations within the square brackets.
>> x = [abs(-4) 4^2] x = 4 16
Creating Evently-Spaced Vectors
It is common to create vectors containing evenly spaced numbers, such as the vector below.
>> y = [5 6 7 8] y = 5 6 7 8
For long vectors, entering individual numbers is not practical. An alternative, shorthand method for creating evenly spaced vectors is to use the : operator and specify only the start and end points: first:last.
>> y = 5:8 y = 5 6 7 8
The : operator uses a default spacing of 1, however you can specify your own spacing, as shown below.
>> x = 20:2:26 x = 20 22 24 26
If you know the number of elements you want in a vector (instead of the spacing between each element), you could instead use the
linspace
function:
linspace(first,last,number_of_elements)
.
Note the use of commas (,
) to separate inputs to thelinspace
function.>> x = linspace(0,1,5) x = 0 0.250 0.500 0.750 1.000
Both linspace and the : operator create row vectors. However, you can convert a row vector into a column vector using the transpose operator (
'
).>> x = 1:3; >> x = x' x = 1 2 3
You can create column vectors in a single command by creating the row vector and transposing it all on one line. Note the use of parentheses here to specify the order of operations.
>> x = (1:2:5)' x = 1 3 5
Array Creation Functions
MATLAB contains many functions that help you to create commonly used matrices, such as matrices of random numbers.
>> x = rand(2) x = 0.8147 0.1270 0.9058 0.9134
Note that the
2
in the commandrand(2)
specifies that the output will be a 2-by-2 matrix of random numbers.Many matrix creation functions allow you to input one number to create a square matrix (n-by-n) or input two numbers to create nonsquare matrices.
>> x = rand(2) x = 0.8147 0.1270 0.9058 0.9134 >> x = rand(2,3) x = 0.6324 0.2785 0.9575 0.0975 0.5469 0.9649
-
Importing Data
Bring data from external files into MATLAB.
Saving and Loading Variables
You can save variables in your workspace to a MATLAB specific file format called a MAT-file using the
save
command.>> save foo x
The command above saves a variable named
x
to a MAT-file namedfoo.mat
.You can load variables from a MAT-file using the
load
command.>> load foo
Indexing into and Modifying Arrays
Use indexing to extract and modify rows, columns, and elements of MATLAB arrays.
Indexing into Arrays
You can extract values from an array using row, column indexing.
>> x = A(5,7);
This syntax extracts the value in the
$5^\textrm{th}$ row and $7^\textrm{th}$ column of A
and assigns the result to the variablex
.You can use the MATLAB keyword
end
as either a row or column index to reference the last element.>> x = A(end,2);
Note that you can use arithmetic with the keyword
end
. For example:>> x = A(end-1,end-2)
Extracting Multiple Elements
When used as an index, the colon operator (
:
) specifies all the elements in that dimension. The syntax>> x = A(2,:)
creates a row vector containing all of the elements from the second row of
A
.The colon operator can refer to a range of values. The following syntax creates a matrix containing the first, second, and third rows of the matrix
A
.>> x = A(1:3,:)
A single index value can be used to reference vector elements. For example
>> x = v(3)
returns the third element of vector
v
whenv
is either a row or column vector.A single range of index values can be used to reference a subset of vector elements. For example
>> x = v(3:end)
returns a subset of vector
v
containing the elements from 3 to the end.Changing Values in Arrays
Elements of a variable can be altered by combining indexing with assignment.
>> A(2,5) = 11
Array Calculations
Perform calculations on entire arrays at once.
Performing Aray Operations on Vectors
MATLAB is designed to work naturally with arrays. For example, you can add a scalar value to all the elements of an array.
>> y = x + 2
You can add together any two arrays of the same size.
>> z = x + y
You can multiply or divide all of the elements of an array by a scalar.
>> z = 2*x >> y = x/3
Basic statistical functions in MATLAB can be applied to a vector to produce a single output. The maximum value of a vector can be determined using the
max
function.>> xMax = max(x)
MATLAB has functions that perform mathematical operations on an entire vector or array of values in a single command.
>> xSqrt = sqrt(x)
The
*
operator performs matrix multiplication. So, if you use*
to multiply two equally sized vectors, since the inner dimensions do not agree, you will get an error message.>> z = [3 4] * [10 20] Error using * Inner matrix dimensions must agree.
In contrast, the
.*
operator performs elementwise multiplication and allows you to multiply the corresponding elements of two equally sized arrays.>> z = [3 4] .* [10 20] z = 30 80
Calling Functions
Call functions to obtain multiple outputs.
Obtaining Multiple Outputs from Function Calls
The
size
function can be applied to an array to produce a single output variable containing the array size.>> s = size(x)
The
size
function can be applied to a matrix to produce either a single output variable or two output variables. Use square brackets ([ ]
) to obtain more than one output.>> [xrow,xcol] = size(x)
The maximum value of a vector and its corresponding index value can be determined using the
max
function. The first output from themax
function is the maximum value of the input vector. When called with two outputs, the second output is the index value.>> [xMax,idx] = max(x)
Obtaining Help
Use the MATLAB documentation to discover information about MATLAB features.
Obtaining Help
You can enter
>> doc fcnName
to get information on any MATLAB function.
The MATLAB documentation contains a lot of good examples and information that can help you when working on your own problems.
Plotting Data
Visualize variables using MATLAB's plotting functions.
Plotting Vectors
Two vectors of the same length can be plotted against each other using the
plot
function.>> plot(x,y)
The
plot
function accepts an additional argument that allows you to specify the color, line style, and marker style using different symbols in single quotes.>> plot(x,y,'r--o')
The command above plots a red (
r
) dashed (--
) line with a circle (o
) as a marker. You can learn more about the symbols available in the documentation for Line Specification.To plot one line on top of another, use the
hold on
command to hold the previous plot while you add another line. You can also use thehold off
command to return to the default behavior.Try closing all open figure windows by issuing the
close all
command.When you plot a single vector by itself, MATLAB uses the vector values as the y-axis data and sets the x-axis data to range from
1
ton
(the number of elements in the vector).The
plot
function accepts optional additional inputs consisting of a property name and an associated value.>> plot(y,'LineWidth',5)
The command above plots a heavy line. You can learn more about available properties in the documentation for Lineseries Properties.
The plot function accepts a property name and property value pair after the plotted arguments and line specifier.
>> plot(x,y,'ro-','LineWidth',5)
Further resources: Line Specifiers | Plotting Functions | Plots
Annotating Plots
Labels can be added to plots using plot annotation functions, such as
title
. The input to these functions is a string. Strings in MATLAB are enclosed in single quotes ('
).>> title('Plot Title')
-
Logical Arrays
Use logical expressions to help you to extract elements of interest from MATLAB arrays.
Logical Operations and Variables
Relational operators, such as
>
,<
,==
, and~=
perform comparisons between two values. The outcome of a comparison for equality or inequality is either 1 (true) or 0 (false).>> pi > 3 ans = 1
Notice that the new logical variable can be seen in the workspace window on the right. Logical variables have one of only two possible values:
1
(true) and0
(false).>> pi > 3 ans = 1
You can compare a vector or matrix to a single scalar value using relational operators. The result is a logical array of the same size as the original array.
>> [5 10 15] > 12 ans = 0 0 1
Corresponding elements of two arrays can be compared using relational operators. The two arrays must be the same size and the result is a logical array of the same size.
>> [5 10 15] > [6 9 20] ans = 0 1 0
Combining Logical Conditions
MATLAB contains logical operators which combine multiple logical conditions such as AND (
&
) and OR (|
). The&
operator returnstrue
(1) if both elements are true, and false (0) otherwise. For example:>> x = (pi > 5) & (0 < 6) x = 0
Logical Indexing
you can use a logical array as an array index, in which case MATLAB extracts the array elements where the index is
true
. The following example will extract all elements inv1
that are greater than six.>> v = v1(v1 > 6) v = 6.6678 9.0698
You can use logical indexing to reassign values in an array. For example, if you wish to replace all values in the array
x
that are equal to999
with the value0
, use the following syntax.x(x==999) = 0
Programming
Write programs that execute code based upon some condition.
Decision Branching
At times, you may want to execute a section of code only if a certain condition is met. You can do this using an
if
statement. Eachif
statement must contain oneif
keyword and oneend
keyword, and code between theif
andend
keywords is executed only when the condition is met.x = rand; if x > 0.5 y = 3; %Executed only if x > 0.5 end
Often in these situations, you may want to execute some other code if the condition is not met. To do this, you can use the
else
keyword, as shown.x = rand; if x > 0.5 y = 3; else y = 4; end
For Loops
A common programming task is to execute a section of code repeatedly. In MATLAB, you can do this with a
for
loop.for i = 1:3 disp(i) end
Notice that the
for
loop contains a singleend
keyword, similar toif
statements.When this code is run, the code between the
for
andend
keywords will be executed three times in this case, as the loop counter (i
) progresses from1:3
(1
,2
, and3
).
-
Matlab要怎么进行仿真,要出版教程么
-
@yzh 你指的什么仿真?
-
弱弱的问一句,matlab和octave对于一般数据分析都够了把