In MATLAB, the most fundamental way to create a new vector is by enclosing the elements you want in the vector within square brackets []
. You can separate the elements using either spaces or commas.
Core Method: Using Square Brackets []
MATLAB treats vectors as matrices with a single row (row vector) or a single column (column vector). According to the provided information, creating a row vector is done by listing its elements inside square brackets.
There are two common ways to separate the elements within the square brackets:
- Using Spaces: Simply put a space between each element.
- Using Commas: Separate each element with a comma.
Both methods result in the exact same outcome: a row vector (a matrix with 1 row and N columns).
Creating a Vector with Spaces
You can define a variable and assign the vector directly to it using spaces to separate the numerical or string elements.
% Create a row vector using spaces
v_space = [10 20 30 40 50];
In this example, v_space
becomes a 1x5 row vector.
Creating a Vector with Commas
Alternatively, you can achieve the identical result by using commas between elements.
% Create a row vector using commas
v_comma = [10, 20, 30, 40, 50];
Here, v_comma
is also a 1x5 row vector, identical in structure and content to v_space
created using spaces.
As stated in the reference: "You can create a vector both by enclosing the elements in square brackets like v=[1 2 3 4 5] or using commas, like v=[1,2,3,4,5]. They mean the very same: a vector (matrix) of 1 row and 5 columns."
Practical Examples
Let's see how this looks in the MATLAB Command Window:
>> myRowVectorSpace = [1 2 3 4 5]
myRowVectorSpace =
1 2 3 4 5
>> myRowVectorComma = [1,2,3,4,5]
myRowVectorComma =
1 2 3 4 5
As demonstrated, assigning [1 2 3 4 5]
or [1,2,3,4,5]
to a variable like myRowVectorSpace
or myRowVectorComma
creates a row vector. Both produce a matrix that has 1 row and 5 columns.
Summary of Methods
Method | Separator | Example | Result |
---|---|---|---|
Square Brackets | Space | v = [1 2 3 4 5]; |
1x5 Row Vector |
Square Brackets | Comma | v = [1, 2, 3, 4, 5]; |
1x5 Row Vector |
This table summarizes the primary ways to create a row vector directly by listing its elements within square brackets in MATLAB, as described in the reference.
Creating vectors using square brackets with elements separated by spaces or commas is a fundamental and widely used method in MATLAB programming.