当前位置:
文档之家› 《MATLAB及其工程应用》第2讲
《MATLAB及其工程应用》第2讲
Subarray
• Select and use subsets of a array
c = [1 2 3; 4 5 6]; a = c(1, [ 2 3]) b = c([1 2], [ 2 3])
• The end function • Assignment to subarray
c(1, 2:end) c(1, [ 2 3]) = [12 13]
Initialize the Array
There are 3 common ways:
• Using assignment statement • Read from a file • From keyboard
Initializing Variables in Assignment Statement
A MATLAB variable is a region of memory containing an array, which is known by a user-specified name.
Naming Rule
• must begin with a letter, followed by any combinations of letters, numbers, and the underscore character. C can begin with ‘_’ !!! • Only the first 31 characters are significant.
Firmly grasp the naming rules of MATLAB variables. Fully grasp the initialize and addressing method of a array. Memorize the basic special variables, such as pi, i, j, ans, NaN. Grasp how to save and load MATLAB variiables with Keyboard Input
• var = input(‘Enter an input value:’)
Multi-dimensional Arrays
• Create a multi-dimensional array
e.g. c is a 2x3x2 array
• Var = zeros(?) • Var = ones(?)
Initializing Variables from file
• MATLAB formatted file
• load xxx.mat • save file_name var1, var2, var3…
• ASCII file
• load file_name.xxx -ascii
• Assigning a scalar to a subarray
c(2, [ 2 3]) = 99
Assignment:
• Excises
2.1, 2.2, 2.3 2.4
• Using assignment statement
• Var = expression
• Initializing with shortcut expression
• Var = first : incr : last
• Initializing with build-in functions
• Must using meaningful names • Include a data dictionary in the header of the program • Use lowercase letters to name a variable • Use underscore as separator if the name is long
• c(:, :, 1) = [1 2 3; 4 5 6]; • c(:, :, 2) = [7 8 9; 0 1 2];
• MATLAB always allocates array elements in column major order.
• a(1, 1, 1) -> a(2, 1, 1) -> a(1, 2, 1) -> a(2, 2, 1) -> a(1, 3, 1)… • a(10) = 1
Special Variables
MATLAB has some predefined variables and users should avoid using them create new variables.
i, j, pi, NaN, ans, eps
Good Programming Practice
MATLAB & Its Applications In Engineering
李清都 副教授 liqd@
Lect. 2: Variables & Arrays
Contents Covered: basic conceptions of MATLAB variables and arrays initialize/save/load MATLAB variables and arrays Objectives:
Arrays
All data, even scalars, are arrays.
• Vectors: 1 dimension • Matrix: 2 or more dimensions
A scalar is an array with only one row and one column.
Variables