Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Software Engineering Tutorial
  • Software Development Life Cycle
  • Waterfall Model
  • Software Requirements
  • Software Measurement and Metrics
  • Software Design Process
  • System configuration management
  • Software Maintenance
  • Software Development Tutorial
  • Software Testing Tutorial
  • Product Management Tutorial
  • Project Management Tutorial
  • Agile Methodology
  • Selenium Basics
Open In App
Next Article:
Set Variable Data Types in MATLAB
Next article icon

Variable Names in MATLAB

Last Updated : 22 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

A variable is a named-memory location that stores different types of data which can be used to perform a specific set of operations. It can be thought of as a container that holds some value in memory. The Matlab workspace store all the variables being used during a session. This workspace not only deals with the creation of new variables but also supports the reusing of existing variables in the execution of the command. Each variable in the Matlab environment is treated as a matrix or an array of different data types. In Matlab, variables are assigned using the assignment '=' operator. 

Note:

  • After the creation of a variable, we can use it later in our program.
  • There must have values assigned to variables before they are used.
  • If an expression returns a result without being assigned to any variable, the system implicitly assigns and stores the value to a special variable named 'ans'. But ans variable is specific to the current workspace and the value of ans can change frequently, that is why the use of ans in a script or function is not recommended.

Example 1: 

Matlab
% MATLAB code for defining a and initializing  % it with a value 10 using assignment operator '=' a = 10  

Output:

a = 10

Example 2:

Matlab
% MATLAB code for calculates an expression % and stores value 13 in variable b b = sqrt(169)    

Output:

b = 13

Example 3:

Matlab
% MATLAB code to stores the expression  % in special variable 'ans' sqrt(169)    

Output:

ans = 13

Rules for creating a variable:

A variable name is the name of the memory location where we can store our values. Some of the rules for naming a variable are:

  • A variable name should start with a letter followed by digits, underscores, or letters.
  • Don't use Matlab keywords as variable names.
  • Matlab is case sensitive, i.e., small letters and capital letters are treated differently. For example, variable names 'PRICE' and Price are different.
  • A variable name cannot contain letters more than name length max characters.
  • Special symbols anywhere in a variable name are syntactically invalid in Matlab.
  • Avoid naming variable names as provided by pre-defined Matlab's variable names.
Examples of valid variable names:Examples of invalid variable names:
Principal8a
F_Value1_Digit
Digit_1Roll_No!
a10end
Roll_noif

Check whether a variable name is a Matlab keyword:

To check whether a variable name is a MATLAB keyword or not, MATLAB provides a built-in function iskeyword( ). This keyword determines whether the input is MATLAB keyword or not.

Syntax:

v = iskeyword(txt)
iskeyword

Example 1:

Matlab
% MATLAB code for check variable % is keyword or not Test=iskeyword('if')  % this statement returns   % logical True (1) as a result as 'if' is a keyword  % in the Matlab otherwise returns false.   iskeyword if  % this statement uses the Matlab  % command format and results in ans=1.             
Test = logical         1    ans = logical        1

Example 2:

Matlab
% MATLAB code for print all keyword iskeyword % returns a list of all Matlab keywords. 

  Output:  

 Check whether the input is a valid variable name:

To check whether the input is a valid variable name isvarname( ) is used. This function determines if the input is a valid variable name. If it is a valid MATLAB variable name the isvarname function returns logical 1 (true). Otherwise, it returns logical 0 (false).

Syntax:

t = isvarname(s)

isvarname s

Example 1:

Matlab
% MATLAB code for isvarname isvarname Number_1 

Output:

ans = logical      1

Example 2:

Matlab
% MATLAB code for isvarname() Test= isvarname(Digit_1) 

Output:

Test = logical        1

Conflicts between variable and function name:

Matlab provides some predefined functions such as pi, ans, i, j, clock, date, eps which cannot be used as variable names as they can create confliction between variable name and functions name.  Usually, variable names take precedence over function names that result in unexpected results.

To check whether a variable name is already used with function:

Example:

Matlab
% MATLAB code for check if there is no % existing variables or functions name. In case it exists,  % remove the variable from the memory with the clear() function.  exist varname  

Output:

ans=0

genvarname()

This function (generate variable name)  is used to construct a valid and unique variable name. It returns an array of strings or characters that can be used as a legal variable name. Argument str can be a string, a string array, a character array, or a cell array containing character vectors. All the returned elements are unique. 

Syntax:

varname = genvarname(str)

varname = genvarname(str, exclusions)

here genvarname(str, exclusions) returns a legal variable name that is different from any name listed in the exclusions input. The argument exclusions can be a string, a string array, a character array, a cell array of character vectors.

Example 1:

Matlab
% MATLAB code for gemvarname() var_name = genvarname({'Pen', 'Pen', 'Pen', 'Pen'}) 

Output:

var_name = 1X4 cell    'Pen_1'   'Pen_2'   'Pen_3'    'Pen_4'

Example 2:

Matlab
% MATLAB code for genvarname() with different parameters a = ["Pen", "Eraser", "Pencil", "Box" ] var_name=genvarname(a,"Box") 

Output:

var_name= 1x4 string  "Pen"  "Eraser"   "Pencil"   "Box1"

 

 

 


Next Article
Set Variable Data Types in MATLAB

S

sheetal18june
Improve
Article Tags :
  • Software Engineering
  • MATLAB-Basic

Similar Reads

  • Variable in Maths
    A variable is like a placeholder or a box that can hold different values. In math, it's often represented by a letter, like x or y. The value of a variable can change depending on the situation. For example, if you have the equation y = 2x + 3, the value of y depends on the value of x. So, if you ch
    5 min read
  • Set Variable Data Types in MATLAB
    There are many cases when a user has to import data into MATLAB script from various files. These file types could be .txt, .xlsx, .csv, .dat, etc. types. Now, each file type has its own method of defining data types. However, for computation purposes, MATLAB requires the data to be of numeric type,
    3 min read
  • Global Variables in MATLAB
    Variables in programming are generally storage spaces to store a certain type of data. There are many types of variables, but two commonly used types are local and Global variables. Generally, each MATLAB function has its own local variables. But sometimes for the sake of programming, we need to cha
    4 min read
  • Clear variable from Memory in MATLAB
    Clearing variables from memory, with the help of clearvars operation. The clearvars operation is used to clear the specified variables from memory or from the currently active workspace. Syntax:clearvars variables clearvars -except keepVariables Parameters: This function accepts a parameter. variabl
    1 min read
  • Set environment variable in MATLAB
    Setting environment variables with the help of setenv() function. The setenv() function is used to set the specified value of an operating system environment variable. Here the environment variable "name" will be replaced with "value", where "name" and "value" is its parameters. Syntaxsetenv(name, v
    1 min read
  • Numeric Types in MATLAB
    Numeric class in MATLAB includes signed and unsigned integers, single-precision floating-point numbers, and double-precision floating-point numbers. Generally, MATLAB stores all numeric values as double-precision floating-point. But, we can choose to store any number, or, an array of numbers, as int
    3 min read
  • Variables in LISP
    Similar to other languages, in LISP variables are named places that store a particular value, but they are not declared the way you declare variables in C++ or Java i.e you don't need to mention data-type of variables when declaring them as LISP is dynamically typed. LISP supports two types of varia
    3 min read
  • Polynomials in MATLAB
    A polynomial is an expression that is made up of variables, constants, and exponents, that are combined using mathematical operations such as addition, subtraction, multiplication, and division (No division operation by a variable). Polynomials in MATLAB are represented as row of a vector containing
    2 min read
  • Mesh Surface Plot in MATLAB
    Mesh Surface Plot is used to depict f(X, Y, Z) in a three-dimensional space. Matlab allows users to create mesh surface plots using the mesh() method. Different syntax of mesh() method are: Mesh(X, Y, Z)Mesh(Z)Mesh(___,C)Mesh(___, Name, Value)S = mesh()Mesh(ax,____)Mesh(X, Y, Z)It plots X, Y, Z on a
    3 min read
  • Nested Switch in MATLAB
    Switch statements in MATLAB allow having multiple cases as conditionals. It is an implementation of the simple if-elif-else-end cycle but, better. In this article, we will see how nested switch statements work in MATLAB with the help of example. Syntax:switch choice_1 case <1> switch choice_2
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences