OKPEDIA MATLAB EN VETTORI

How to extract elements from a vector in Matlab and Octave

To extract a group of elements from a vector in Matlab and Octave type

v(x:y)

  • The first parameter x is the position of the first element of the group
  • The second parameter y is the position of the last element of the group

The function returns a vector composed of the elements between the x and y positions.

Note. To extract a group of elements in non-continuous position type v ([x1, x2, x3, ...]) The terms x1, x2, x3 ... are the individual positions of the elements to be extracted from the vector.

Examples

Example 1

Define a vector with 5 elements

>> v=['a';'b';'c';'d';'e']

To extract the elements from the second to the fourth type v(2:4)

>> v(2:4)
ans =
b
c
d

Matlab / Octave extracts a group of three elements from the vector.

Example 2

To extract elements from second to last element

>> v(2:end)
ans =
b
c
d
e

In this case, the position of the final element is not explicitly expressed, because the term "end" automatically indicates the last position of the vector.

Example 3

To extract the first, third and fifth elements of the vector

>> v([1,3,5])
ans =
a
c
e

The elements 'a', 'c', 'and' are not in continuous positions. They are separated by other elements.

To extract non-continuous elements, indicate the individual position of each element in square brackets. Separate each element from the next with a comma.

Example 4

To extract vector elements in odd position

>> v(1:2:end)
ans =
a
c
e

The first and third parameters respectively indicate the position of the first (1) and last (end) element to be extracted from the vector.

The second element indicates the extraction step (2). In this case, one element for every two elements.

Example 5

To extract the penultimate element and last element of a vector

>> v(end-1:end)
ans =
d
e

The command extracts the last element (end) and the penultimate element (end-1) from the vector

https://how.okpedia.org/en/matlab/how-to-extract-elements-from-a-vector-in-matlab-and-octave


Report us an error or send a suggestion to improve this page


Arrays and Vectors


FacebookTwitterLinkedinLinkedin