How to Insert Data Into a Vector in MATLAB - MATLAB
Video Player is loading.
Current Time 0:00
Duration 2:18
Loaded: 7.17%
Stream Type LIVE
Remaining Time 2:18
 
1x
  • Chapters
  • descriptions off, selected
  • en (Main), selected
    Video length is 2:18

    How to Insert Data Into a Vector in MATLAB

    Learn how to insert additional values into a vector in MATLAB. When working with an existing data set of any size, you may encounter a scenario that requires you to insert values into an existing vector. With the use of logical indexing, also known as conditional data indexing, you can easily insert values into an existing vector. 

    Published: 28 Jan 2021

    By now, you know how to make vectors in MATLAB. But what happens if you have additional values you want to insert into a vector? When working with an existing data set of any size, you may encounter a scenario that requires you to insert values into an existing vector. With the use of logical indexing, also known as conditional data indexing, you can easily insert values into an existing vector. Let's take a look at an example in MATLAB.

    Let's start with the vector a that includes real numbers 0 through 10. Now let's assume that we want to insert the product of a random number multiplied by 10 called b. We'll use the random function to generate the random number and multiply it by 10.

    Here we have b, the number we want to insert in our existing vector, a. In order to insert the value b into a, we must use logical indexing. Now, if you're using these commands in a function or a loop, you may want to include the semicolon operator at the end of the command line to suppress the output. For this example, I want you to see the output. So I'll admit the semicolon.

    First, will identify the indices in a less than b. We'll call viBelow. Here, you'll see the index values in a that are less than b as 1's and values that are equal to or larger than b as 0's.

    Now we'll create a new vector called newA as the concatenation of the three vectors. a indexed as viBelow, b, and the values of a that are not indexed as viBelow using the tilde operator. And there you have it. You can see b inserted a in ascending order.

    These commands can be integrated within functions and loops to insert any number of values into an existing vector. For more information on working with vectors, functions, loops, and logical indexing, also known as conditional data indexing, be sure to check out our additional videos and help documentation.

    Related Products

    Related Information

    View more related videos