Trending December 2023 # How To Use Excel Vba Split Function? # Suggested January 2024 # Top 16 Popular

You are reading the article How To Use Excel Vba Split Function? updated in December 2023 on the website Tai-facebook.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How To Use Excel Vba Split Function?

VBA Split Function

As the name suggests, a Split is a function that splits strings into different parts. We have many such functions in excel worksheets, such as a left-right and mid function to do so. But when we need any string to differentiate in parts, we use a Split function in VBA. It is one of the best functions in VBA to perform different types of operations on strings.

The split function is basically a substring function that takes a string as an input and gives another string as an output. The only difference between the other substring function like left, right, and mid and split function is that the LEFT, RIGHT & MID function just take one string as an input or argument and returns one string as an output while the SPLIT function returns an array of strings as output.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Formula for Split Function in Excel VBA

VBA Split function has the following syntax:

Given below are the arguments for the VBA split function first:

Expression as String: This is a mandatory argument in VBA Split function. Expression as string refers to the string we want to break into parts.

Delimiter: This is an optional argument. It is the character that is used to break strings into parts. But if we do not provide any delimiter, VBA treats space “ “ as default delimiter.

Limit: This is also an optional argument. Limit means the maximum number of parts we want to do of a string. But again, if we do not provide a limit to the function, VBA treats it as default -1, which means the string will break apart each time there is a delimiter in the string.

Compare: This final argument is also an optional argument. Compare is a method that is described as one of the two below:

Either it is 0, which means Split will perform a binary comparison which means every character should match itself.

Or it can be 1, which means the Split function will do a textual comparison.

Everything will be clear in a few examples. But let me give a very basic example first of what this function does. Suppose we have an input string as ANAND IS A GOOD BOY. The split string will break it into parts, each word separately. We can also use the Split function to count a number of words in a string, or we can use it to output only a certain amount of words in a given string.

How to Use Excel VBA Split Function?

We will see how to use a VBA Split Excel function with few examples:

You can download this VBA Split Excel Template here – VBA Split Excel Template

VBA Split Function – Example #1

How about we use the above string ANAND IS A GOOD BOY with split function.

Note: In order to use a Split function in VBA, make sure that the developer option is turned on from File Tab from the options section.

Step 3: When the code window appears, declare a sub-function to start writing the code.

Code:

Sub

Sample()

End Sub

Step 4: Declare two variables arrays and one as strings A & B.

Code:

Sub

Sample()

Dim

A

As String

Dim

B()

As String

End Sub

Step 5: Store the value of the string in A.

Code:

Sub

Sample()

Dim

A

As String

Dim

B()

As String

A = "ANAND IS A GOOD BOY"

End Sub

Step 6: In the B array, store the value of A using the split function as shown below.

Code:

Sub

Sample()

Dim

A

As String

Dim

B()

As String

A = "ANAND IS A GOOD BOY" B = Split(A)

End Sub

Step 7: Use For Loop to break every string.

Code:

Sub

Sample()

Dim

A

As String

Dim

B()

As String

A = "ANAND IS A GOOD BOY" B = Split(A)

For

i =

LBound

(B)

To UBound

(B) strg = strg & vbNewLine & "String Number " & i & " - " & B(i)

Next

i

End Sub

Step 8: Display it using the Msgbox function.

Code:

Sub

Sample()

Dim

A

As String

Dim

B()

As String

A = "ANAND IS A GOOD BOY" B = Split(A)

For

i =

LBound

(B)

To UBound

(B) strg = strg & vbNewLine & "String Number " & i & " - " & B(i)

Next

i MsgBox strg

End Sub

Step 9: Run the code from the run button provided below.

We get this as output once we run the above code.

VBA Split Function – Example #2

We will now try to take input from a user and split the string into parts.

Step 3: In the code window, declare a sub-function to start writing the code.

Code:

Sub

Sample1()

End Sub

Step 4: Declare two variables, one as String and one as an Array String.

Code:

Sub

Sample1()

Dim

A

As String

Dim

B()

As String

End Sub

Step 5: Take the value from the user and store it in the A using the Inputbox function.

Code:

Sub

Sample1()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces")

End Sub

Step 6: Store the value of A in Array B using the Split Function.

Code:

Sub

Sample1()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces") B = Split(A)

End Sub

Step 7: Use For Loop to break every string.

Code:

Sub

Sample1()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces") B = Split(A)

For

i =

LBound

(B)

To UBound

Next

i

End Sub

Step 8: Display it using the Msgbox function.

Code:

Sub

Sample1()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces") B = Split(A)

For

i =

LBound

(B)

To UBound

(B) strg = strg & vbNewLine & "String Number " & i & " - " & B(i)

Next

i MsgBox strg

End Sub

Step 9: Run the code from the run button. Once we run the code, we get an input message to write a string. Write “I AM A GOOD BOY” as input in the input box and press ok to see the result.

VBA Split Function – Example #3

We can also use the VBA Split Function to count the number of words in the string. Let us take input from the user and count the number of words in it.

Step 3: Once the code window is open, declare a sub-function to start writing the code.

Code:

Sub

Sample2()

End Sub

Step 4: Declare two variables, one as a string and one as an array string.

Code:

Sub

Sample2()

Dim

A

As String

Dim

B()

As String

End Sub

Step 5: Take input from the user and store it in A using the input box function.

Code:

Sub

Sample2()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces")

End Sub

Step 6: Use the Split function and store it in B.

Code:

Sub

Sample2()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces") B = Split(A)

End Sub

Step 7: Use a Msgbox function to display the total number of words.

Code:

Sub

Sample2()

Dim

A

As String

Dim

B()

As String

A = InputBox("Enter a String", "Should Have Spaces") B = Split(A) MsgBox ("Total Words You have entered is : " &

UBound

(B()) + 1)

End Sub

Step 8: Run the code from the run button provided. Once we have run the code, it asks for an input for the string. Write “INDIA IS MY COUNTRY” in the box and press ok to see the result.

Explanation of Excel VBA Split Function

Now we know that the split function in VBA is a substring function that is used to split strings into different parts. The input we take is as a string, while the output displayed is an array.

It is very similar to the other worksheet function, but it is superior as it can break multiple words and return them as an array.

Things to Remember

There are a few things we need to remember about VBA split function:

The VBA split function is a substring function.

It returns the output as a string.

Only the expression is the mandatory argument, while the rest of the arguments are optional.

Recommended Articles

This has been a guide to VBA Split Function. Here we discussed how to use Excel VBA Split Function along with practical examples and a downloadable excel template. You can also go through our other suggested articles to learn more –

You're reading How To Use Excel Vba Split Function?

How To Use Excel Vba Instrrev With Examples?

VBA InStrRev Function

Knowing the occurrence of a string in another string can be very handy while working with day to day data. Obviously, we can do it manually by calculating the occurrence of the string in another string but that would the task very hefty. So to make it easier we have a function in VBA which is known as INSTRREV which is used to find the occurrence.

As explained above, INSTRREV in Excel VBA is used to find an occurrence of a string in another string. This function finds the first occurrence of a string in the target string and returns the value. Now we have to remember that as it gives the occurrence of the string so the returned value is numeric. Also as it is a comparison function so like other functions in VBA there are three basic comparisons methods.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax of InStrRev in Excel VBA

The syntax for VBA InStrRev function in excel is as follows:

Now let us break down the syntax and learn about it, String is the main string from where we want to find the occurrence of a substring, Start is the numeric occurrence we provide to the string. If no start parameter is provided the function starts looking a string from the end of it. And compare is the comparison method we provide to the function. There are three types of comparison for this function:

To use Option Compare which is (-1). It is also known as VbUseCompareOption.

To use Binary Compare which is (0). It is also known as VbBinaryCompare.

To use Text Compare which is (1). It is also known as VbTextCompare.

Again if none of the compare options is provided then the function automatically considers it as a binary compare.

Now let us use this function in a few examples and look at how to use this function.

How to Use Excel VBA InStrRev?

Now let us try with some examples on VBA InStrRev in Excel.

You can download this VBA InStrRev Excel Template here – VBA InStrRev Excel Template

Example #1 – VBA InStrRev

Step 2: Once we enter the VB editor we can see in the header section, there is an option of insert. Insert a new module from that option as shown below.

Step 3: Now let us start our subprocedure in the module as shown below.

Code:

Sub

Sample()

End Sub

Step 4: Now declare a variable as an integer which will hold the output value of the function for us.

Code:

Sub

Sample()

Dim

A

As Integer

End Sub

Step 5: Now in the variable use the INSTRREV function to find the occurrence of “ “ in the string “ I am a Good Boy” as follows.

Code:

Sub

Sample()

Dim

A

As Integer

A = InStrRev(" I am a Good Boy", " ")

End Sub

Step 6: Now display the value stored in variable A using the msgbox function.

Code:

Sub

Sample()

Dim

A

As Integer

A = InStrRev(" I am a Good Boy", " ") MsgBox A

End Sub

Step 7: Let us execute the above code to get the following result.

We get the result as 13 because we did not provide the start position to the function so it automatically calculated the occurrence from the end and so the result. It is found that “ “ is on the 13th position of the string when we search it from the end.

Example #2 – VBA InStrRev

In the above example, we did not provide any start position to the string. Let us provide this time in this example. Let us find out from the second position where does the “ “ occurs in the string.

Step 1: Insert a new module from that option as shown below.

Step 2: Let us again define a subprocedure for our second example.

Sub

Sample1()

End Sub

Step 3: Declare another integer variable for the example.

Code:

Sub

Sample1()

Dim

A

As Integer

End Sub

Step 4: Now in Variable A let us find the occurrence of the “ “ from the second position using the INSTRREV function as follows.

Code:

Sub

Sample1()

Dim

A

As Integer

A = InStrRev(" I am a Good Boy", " ", 2)

End Sub

Step 5: Now use msgbox function to display the value stored in A.

Code:

Sub

Sample1()

Dim

A

As Integer

A = InStrRev(" I am a Good Boy", " ", 2) MsgBox A

End Sub

Step 6: Now run the above code to find out the below result as shown below,

We get 1 as a result as we count 2 we get I and after one position we get the occurrence of “ “.

Example #3 – VBA InStrRev

In this example let us use the compare methods. We have a string “ India is the Best” and let us find the string “E” using both text and binary compare methods.

Step 1: In the same module 1, write another subprocedure for example 3.

Code:

Sub

Sample2()

End Sub

Code:

Sub

Sample2()

Dim

A, B

As Integer

End Sub

Step 3: In variable A let us use the INSTRREV function with the text comparison as follows.

Code:

Sub

Sample2()

Dim

A, B

As Integer

A = InStrRev("India is the Best", "E", , vbTextCompare)

End Sub

Step 4: Now display the value stored in A using the msgbox function.

Code:

Sub

Sample2()

Dim

A, B

As Integer

A = InStrRev("India is the Best", "E", , vbTextCompare) MsgBox A

End Sub

Step 5: In variable B let’s use the binary comparison for the same string as follows.

Code:

Sub

Sample2()

Dim

A, B

As Integer

A = InStrRev("India is the Best", "E", , vbTextCompare) MsgBox A B = InStrRev("India is the Best", "E", , vbBinaryCompare) MsgBox B

End Sub

Step 6: Execute the above code to find the first result stored in variable A which is as follows.

Step 7: Press OK to see the result stored in variable B.

We get 0 as the result for binary compare because in our string “e” is present not “E”. In binary values both of these are different. So if a value is not found in the string we get a result as 0.

Things to Remember

The value returned by this function is numeric.

If the substring is not found the value returned is 0.

Start position is optional. If it is not provided, by default function search the occurrence from the end of the string.

The comparison methods are also optional.

Recommended Articles

This is a guide to VBA InStrRev. Here we discuss how to use Excel VBA InStrRev along with practical examples and downloadable excel template. You can also go through our other suggested articles –

How To Use Resize Property In Excel Vba Programming?

Excel VBA Resize

VBA Resize is a method where we use it to highlight the cells by changing their size for visualization. The important thing which needs to be noted is that this method is used only for illustration purposes. Resize is a property that is used with the range property method to display the selection of rows and columns provided as an argument concerning a given range.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax of VBA Resize:

The syntax for this property is as follows:

Row size is the number of rows we want to select or highlight, and column size is the number of columns we want to select and highlight. This property needs a reference to a range. If one of the arguments from row size or column size is not provided, this function selects the entire row or the column from the range. The methods to use Resize property in VBA are as follows:

First, we need to provide a range for reference.

The next step is to provide the arguments for the rows and size for resize property.

To illustrate it, we need to use the select property method.

Using the Resize Property in Excel VBA

The following examples will teach us how to use Resize Property in Excel using the VBA Code.

You can download this VBA Resize Excel Template here – VBA Resize Excel Template

Example #1

Let us first begin with the essential resize property. In this example, we will see how to use resize the property and how we need to provide the inputs for this resize function in general. For this, follow the below steps:

Step 2: Now write the sub-procedure for VBA Resize.

Code:

Sub

Example1()

End Sub

Step 3: Resize is a range property of VBA; let us select a range.

Code:

Sub

Example1() Range("A1")

End Sub

Step 4: After that, we can use the dot operator and resize method to select the number of columns and rows.

Code:

Sub

Example1() Range("A1").Resize(RowSize:=2, ColumnSize:=2)

End Sub

Step 5: We can use the select method property for illustration purposes.

Code:

Sub

Example1() Range("A1").Resize(RowSize:=2, ColumnSize:=2).Select

End Sub

Step 6: Run the Code by hitting F5 or the Run button and see the result in worksheet 1.

We have selected two rows and two columns for the range.

Example #2

In the above example, we have used the same number of rows and columns for the range. Let us try a different approach and use diverse selection such as row size to be 3 and column size to be 2. For this, follow the below steps:

Step 1: We can use the same Module and begin with our sub-procedure for the second example.

Code:

Sub

Example2()

End Sub

Step 2: As this is a range property, we will use the range method to reference a cell.

Code:

Sub

Example2() Range("A1:C4")

End Sub

Step 3: Then, we will use the resize method and select the row and column size for the arguments.

Code:

Sub

Example2() Range("A1:C4").Resize(3, 2)

End Sub

Step 4: The final step is to use the Select property method for the illustration.

Code:

Sub

Example2() Range("A1:C4").Resize(3, 2).Select

End Sub

Step 5: When we execute the above code by hitting F5 we can see the following result in sheet 1.

Out of the range A1:C4, this code has selected three rows and two columns.

Example #3

So in the above examples, we saw how to resize property works if there is the same number of rows and columns or a different number of rows and columns as the argument. Now let us see what happens when we do not provide one of the arguments to the function. For this, follow the below steps:

Step 1: Declare another Subprocedure.

Code:

Sub

Example3()

End Sub

Step 2: Now, we can select any random range.

Code:

Sub

Example3() Range("A1:C4")

End Sub

Step 3: Now, we will use the resize property, but we will remove the row specification from the code.

Code:

Sub

Example3() Range("A1:C4").Resize(, 1)

End Sub

Step 4: Now, we will use the select method.

Code:

Sub

Example3() Range("A1:C4").Resize(, 1).Select

End Sub

Step 5: Run the Code by hitting F5 or the Run button.

It selected one column but the entire four rows.

Example #4

Step 1: Let us begin with a sub-procedure in the same Module.

Code:

Sub

Example4()

End Sub

Step 2: First, we activate sheet 1 using the worksheet property method.

Code:

Sub

Example4() Worksheets("Sheet1").Activate

End Sub

Step 3: Now, let us provide the selection with the number of rows and a number of columns using the selection property method, as shown below.

Code:

Sub

Example4() Worksheets("Sheet1").Activate numRows = Selection.Rows.Count numColumns = Selection.Columns.Count

End Sub

Step 4: Now, we can use the resize property to increase the selection by two rows and two columns.

Code:

Sub

Example4() Worksheets("Sheet1").Activate numRows = Selection.Rows.Count numColumns = Selection.Columns.Count Selection.Resize(numRows + 2, numColumns + 2).Select

End Sub

Step 5: So here is our selection before the execution of the code.

Code:

Step 6: When we execute the code.

The following code extended the selection by two rows and two columns.

Things to Remember

There are a few things that we need to remember about VBA Resize:

This is a range property method.

It illustrates the selection of rows and columns from a given range.

The first argument in this function is a row reference, and the second argument is a range reference.

If one of the arguments from row size or column size is not provided, this function selects the entire row or the column from the range.

Recommended Articles

This is a guide to the VBA Resize. Here we discuss how to use the Resize property in Excel VBA, practical examples, and downloadable Excel template. You can also go through our other suggested articles –

How To Create A Vba Macro Or Script In Excel

Microsoft Excel enables users to automate features and commands using macros and Visual Basic for Applications (VBA) scripting. VBA is the programming language Excel uses to create macros. It will also execute automated commands based on specific conditions.

Macros are a series of pre-recorded commands. They run automatically when a specific command is given. If you have tasks in Microsoft Excel that you repeatedly do, such as accounting, project management, or payroll, automating these processes can save a lot of time.

Table of Contents

In this article, we will explain the following:

Enabling Scripts & Macros

How to Create a Macro in Excel

Specific Example of a Macro

Learn More About VBA

Create a Button to Get Started with VBA

Add Code to Give the Button Functionality

Did it Work?

Enabling Scripts & Macros

Before you can create macros or VBA scripts in Excel, you must enable the Developer tab on the Ribbon menu. The Developer tab is not enabled by default. To enable it:

Put a tick in the box next to Developer.

Make sure the document is from a trusted source if you are working on a shared project in Excel and other Microsoft programs.

When you are done using your scripts and macros, disable all macros to prevent potentially malicious code from infecting other documents.

Create a Macro in Excel

All the actions you take in Excel while recording a macro are added to it. 

Enter a Macro name, a Shortcut key, and a Description. Macro names must begin with a letter and can’t have any spaces. The shortcut key must be a letter.

Decide where you want to store the macro from the following options:

Personal Macro Workbook: This will create a hidden Excel document with stored macros to be used with any Excel documents.

New Workbook: Will create a new Excel document to store the created macros.

This Workbook: This will only be applied to the document you are currently editing.

Specific Example Of a Macro

You can manually change this. Or you can create a program using a macro to automatically format it correctly for you.

Record The Macro

This will highlight the cells that have a balance due. We added a few customers with no balance due to further illustrate the formatting.  

Apply The Macro

When you run a macro, all the formatting is done for you. This macro we just created is stored in the Visual Basic Editor.

Users can run macros in several different ways. Read Run a macro to learn more.  

Learn More About VBA

The code you see in the box above is what was created when you recorded your macro. 

Create a Button To Get Started With VBA

To insert a button element, navigate to the Developer tab. 

Select ActiveX Command Button from the dropdown next to Insert in the Controls section.

Add Code To Give The Button Functionality

VBA coding doesn’t take place in the Excel interface. It is done in a separate environment.  

Go to the Developer tab and make sure Design Mode is active.

Looking at the code in the screenshot below, notice the beginning (Private Sub) and end (End Sub) of the code is already there.

The code below will drive the currency conversion procedure.

ActiveCell.Value = (ActiveCell * 1.28)

The screenshot below shows you how the code looks in the VBA window after you insert it .

Did It Work?

Excel Date Function (Formula, Examples)

The date function in Excel is quite helpful for creating dates that consider Month, Year, and Day. We can feed any number here, and the Date function will create the date with respect to the value we feed in. This function is quite useful and helpful for structuring the date standards when we have multiple dates in multiple formats, and we want to standardize this with a single type for all.

Start Your Free Excel Course

Excel functions, formula, charts, formatting creating excel dashboard & others

Let us look at the below simple examples. First, enter the number 43434 in Excel and give the format DD-MM-YYY.

Once the above format is given, look at how Excel shows that number.

Now give the format as [hh]:mm: ss and the display will be as per the below image.

So Excel completely works on numbers and their formats.

We can create an accurate date using the DATE Function in Excel. For example, =DATE (2023, 11, 14) would give the result as 14-11-2023.

The Formula for the DATE Function in Excel is as follows:

The Formula of the DATE function includes 3 arguments, i.e., Year, Month, and Day.

1. Year: It is the mandatory parameter. A year is always a 4-digit number; since it is a number, we need not specify the number in any double quotes.

2. Month: This is also a mandatory parameter. A month should be a 2-digit number that can be supplied either directly to the cell reference or direct supply to the parameter.

3. Day: It is also a mandatory parameter. A day should be a 2-digit number.

How to Use the DATE Function in Excel?

This DATE Function in Excel is very simple and easy to use. Let us now see how to use the DATE Function in Excel with the help of some examples.

You can download this DATE Function Excel Template here – DATE Function Excel Template

Example #1

From the below data, create full date values. In the first column, we have days; in the second column, we have a month; and in the third column, we have a year. We need to combine these three columns and create a full date.

Enter the above into an Excel sheet and apply the below formula to get the full date value.

The Full DATE value is given below:

Example #2

Find the difference between two days in terms of Total Years, Total Months, and Days. For example, assume you are working in an HR department in a company, and you have employee joining date and relieving date data. Next, you need to find the total tenure in the company. For example, 4 Years, 5 Months, and 12 Days.

Here we need to use the DATEDIF function to get the result as per our wish. DATE function alone cannot do the job for us. If we just deduct the relieving date from the joining date, we get the only number of days they worked; we get it in detail.

To get the full result, i.e., Total Tenure, we need to use the DATEDIF function.

DATEDIF function is an undocumented formula where there is no IntelliSense list for it. This can be useful to find the difference between year, month, and day.

The formula looks like a lengthy one. However, I will break it down in detail.

Part 1: =DATEDIF (B2, C2, “Y”) This is the starting date and ending date, and “Y” means we need to know the difference between years.

Part 2: &” Year” is added to a previous part of the foSo, forla. For example, if the first part gives 4, the result will be 4 Years.

Part 3: &DATEDIF(B2, C2, “YM”) Now, we found the difference between years. We find the difference between the months in this part of the formula. “YM” can give the difference between months.

Part 4: &” Months” This is the addition to part 3. If the result of part 3 is 4, then this part will add Months to part 3, i.e., 3 Months

Part 6: &” Days” is added into part 5. If the result from part 5 is 25, it will add Days. I.e., 25 Days.

Example #3

Now I will explain to you the different date formats in Excel. There are many date formats in Excel; each shows the result differently.

VBA Example with Date in Excel:

Assume you are in the welfare team of the company, and you need to send birthday emails to your employees if there are any birthdays. However, sending each one of them is a tedious task. So here, I have developed a code to auto-send birthday wishes.

Below is the list of employees and their birthdays.

I have already written a code to send birthday emails to everyone if there is any birthday today.

Write the above in your VBA module and save the workbook as a macro-enabled workbook.

Once the above code is written on the VBA module, save the workbook.

You only need to add your data to the Excel sheet and run the code every day you visit an office.

Things to Remember

We can supply only numerical values. Anything other than numerical values, we will get an error as #VALUE!

Excel stores dates as serial numbers and displays them according to the format.

Always enter a full-year value. Do not enter shortcut years like 18, 19, 20, etc. Instead, enter the full year 2023, 2023, and 2023

Recommended Articles

This is a guide to Excel DATE Function. Here we discuss the DATE Formula in Excel and how to use the DATE Function in Excel, along with Excel examples and downloadable Excel templates. You may also look at these useful functions in Excel –

How To Use Unique Function To Obtain Unique Values?

Introduction to MATLAB Unique

MATLAB is a programming environment that is interactive and is used in scientific computing. It is extensively used in a lot of technical fields where problem-solving, data analysis, algorithm development, and experimentation is required. The software which are discipline specific are extensively written using MATLAB. These are organized into libraries called toolboxes. MATLAB has also found extensive use in the field of technical education. Where it is used as a base for doing work in computational laboratories.

MATLAB provides us with a lot of mathematical functions, useful in various computational problems. In this article, we will study a powerful MATLAB function called ‘Unique’ As the name suggests, a unique function helps us in getting the ‘unique’ value present in an array.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

Let us understand the Syntax of Unique function in MATLAB.

U = unique(c)

U = unique(c, setOrder)

U = unique(c, occurrence)

Now let us understand all these one by one with the help of different examples.

Unique Functions in MATLAB

Below are the functions in MATLAB:

1. U = unique(c)

This function will result in an array of unique values if the input array has some repeated values in it

Also, the unique function will sort the output array.

Unique Function will result in all unique rows of C if C is a table

This is a simple example without any negative value

c = [1 2 1 6];

This array of numbers is then passed as an argument to our function unique(c)

U= unique(c)

The Output that we obtain will be an array of dimensions 1×3.

This is how our input and output will look like in MATLAB console:

Code:

U= unique(c)

Output:

As we can clearly see in the output, only the unique values are selected from the input array by our Unique function.

Let us now take an example with negative values and see if our function works as expected.

c = [-1 -5 -1 6];

This array consisting of both positive and negative numbers is then passed as an argument to our function unique(c)

U= unique(c)

The Output that we obtain will be an array of dimensions 1×3.

This is how our input and output will look like in MATLAB console:

Code:

U= unique(c)

Output:

 2. U = unique(c,setorder)

Here ‘setorder’ can take values as ‘stable’ or ‘sorted’, ‘sorted’ being the default order

If we keep ‘setorder’ as ‘stable’, the output will be of the order of ‘c’. i.e the sorting will not be performed by ‘unique’ function.

Let us understand this with an example:

A = [1 5 1 2];

In this example, we will keep ‘setorder’ as ‘stable’.

This array of numbers is then passed as an argument to our function unique(c, stable).

C = unique(A,'stable')

The output will be an array of dimensions 1×3.

This is how our input and output will look like in MATLAB console:

Code:

C = unique(A,’stable’)

Output:

As we can observe in the output, the values obtained are not sorted and have the default order.

In the next example, we will keep ‘setorder’ as ‘sorted’ with the same input array as in the above example.

Code:

The output will be an array of dimensions 1×3

This is how our input and output will look like in MATLAB console:

Output:

We can clearly observe the difference here. The values in this example are sorted as expected.

3. U = unique(c,occurrence)

This function will help us in getting the indices of the repeated values in the input array.

’occurrence’ can take 2 values, ‘first’ or ‘last’

‘first’ is the default value and will return the ‘first’ index of the repeated value

‘last’ will return the ‘last’ index of the repeated value

Let us understand this with an example:

C= [1 1 4 4  4  9]; is our input array

This is how our input and output will look like in MATLAB console:

Input:

[C, iC] = unique([1 1 4 4 4 9], ‘last’)

Output:

As we can observe from the output, we not only get the unique values in the input array, but also the indices of unique values. Here, please observe carefully that since we have passed ‘last’ as an argument, for repeated values, the index obtained is ‘last’ index of the repeated value.

Conclusion

So, in this article, we learned how the unique function works in MATLAB. We can use a unique function to obtain the unique values present in the input array. As an additional feature, a unique function also sorts the output. Although, as we learned, we can control this sorting behavior of the unique function.

Recommended Articles

This is a guide to Matlab Unique. Here we discuss the Introduction to Matlab Unique and its different Examples as well as its Code and output. You can also go through our suggested articles to learn more –

Update the detailed information about How To Use Excel Vba Split Function? on the Tai-facebook.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!