Matlab Array - Creating
Creating
- The methods below create new arrays directly; they do not include constructing a new array by combining, concatenating, or slicing an existing one.
Direct Construction
Use square brackets [] together with commas , (or spaces) and semicolons ;:
- List all elements inside
[] - Within a row, separate elements with
,or whitespace - Separate rows with
;
Row Vectors
- Arithmetic sequences
- Operator
::<[start:<step>:end]>- All three operands are
double - step defaults to 1
- end need not be ≥ start; in that case step must be negative, otherwise the result is empty
- The first element of the result is start; the last is
start + floor((end - start) / step) * step
- All three operands are
- Function linspace
- Operator
- Geometric sequences
- Function logspace
Column Vectors
- Transpose operator
'
2-D Arrays
A = [1 2 3; 2 5 6; 1 4 5];
B = [1:5; linspace(3, 10, 5); 3 5 2 6 4];
C = [[1:3]' linspace(2, 3, 3)' [3 5 6]'];Special Arrays
- Zero array: function Matlab Functions - zeros
- Ones array: function
ones- Same syntax as zeros, with 0 replaced by 1
- Identity array: function
eye- Same syntax as zeros; 1 on the main diagonal, 0 elsewhere
- Cannot create N-D (more than 2-D) arrays
- Uniformly distributed random array: function
rand- Same syntax as zeros, with 0 replaced by samples drawn uniformly on
- However,
typenamemay only besingleordouble
- Normally distributed random array: function
randn- Same as
rand, with the uniform distribution on replaced by the standard normal distribution on
- Same as
- Logical array: functions
trueandfalse- Same syntax as zeros, with 0 replaced by logical 1/0; produces a logical array
- Therefore there is no
typenameparameter
- Diagonal array: function diag
- Magic square: function magic