Categories

# Variables and global Variables

## Variables

The variables, created in MATLAB code are handled by its workspace and used to define memory locations and store values assigned to each respective variable. Matlab workspace supports creating new variables as well as reusing of existing variables in command execution. In the Matlab environment, each variable is treated as a matrix or an array irrespective of their data types.

## Declaring variables in Matlab

Matlab does not need variables to be declared explicitly. When the user specifies the variable name followed by equation and data, a variable with the given variable name is instantiated holding the assigned data within.

The data can be assigned to a variable in ways:

## 1. Assigning a constant value to the variable

### Code:

var1 = 15.41
var2 = [10 22 43; 40 45 63; 27 48 19]

var1 = sqrt(16)
var2=sin(1)

## 3. Initializing variables in Matlab

Matlab variables are initialized with the initial value assigned to it. Matlab variables support both empty and non-empty data as initial values.

### Code:

var1 = [] var2=10

## How do Variables work in Matlab?

Once a variable is created from code, Matlab adds the variables to the workspace.

### Code:

var1="I am variable";
I = [1 2 3; 4 5 6; 7 8 9];

### Output:

Explanation: The content of the variable can be edited using command or can be edited from the variable editor. Apart from editing, the other operations such as deleting, duplicating, copying, resizing, or reshaping the variable can be done in the workspace.

Multiple variables can be declared in a single command line from the Matlab command window.

### Code:

var1=50;var2=60;var3=70;

## Types of variables in Matlab

Various data types are supported by Matlab variables, such as:

## 1. Char

The array of characters is supported by Matlab variables.

### Code:

char_var = "I am a char type variable";
char_var_arr = ["charset1","charset2","charset3"];

## 2. Complex

The complex variables i.e. in the form of “real +i*imaginary” are supported by Matlab variables.

### Code:

complex_var = complex(5,10);

### Code:

real = uint8([11;25;23;40]);
imgainary = uint8([21;25;27;47]);
complex_arr = complex(real,imgainary)

## 3. Double

In Matlab, the default numeric data type or class is ‘double’, which provides high precision for most of the computational tasks. Numeric variables are captured in the form of 64-bit (8-byte) double-precision floating-point value automatically.

### Code:

var_name = 100;
xtype = class(var_name)

### Output:

It supports variable datatype conversion to double.

### Code:

other_var = true
other_var_double = double(other_var);
other_var_newtype = class(other_var_double)

## 4. Signed integer

Matlab supports variable arrays that of the singed integer data type. The variables can be defined as 8/16/32/64-bit signed integer depending on the size of the data.

### Code:

var_int8 = int8(50) ; var_int16 = int16(50); var_int32 = int32(50); var_int64 = int64(50);

## 5. Logical

Logical value can be used in Matlab programming in the form of a variable. But Complex values and NaNs are not supported for logical value conversion and throws conversion error.

Any non-zero element gets converted as logical 1 i.e. Boolean true and 0 gets converted as logical 0 i.e. Boolean false.

### Code:

A = [10 -23 0;35 42 71; -28 0 36];
L = logical(A)

### 6. Single

Matlab supports Single-precision variable declaration and those get stored as ‘single’ datatype 4-byte (32-bit) floating-point values.

### Code:

single_var= single(100)
vartype = class(single_var)

## 7. Structure

A structure array can be defined as a data type that allows grouping related data using data containers which are termed as fields and can be used as a user-defined data type. A field can contain data of any Matlab supported data type of class.

The data of a field can be accessed using dot notation form as given as ‘structName.fieldName’.

### Code:

struct_var = struct

### Code:

field_name = 'field_name';
values = {'A string';
[15, 25, 35];
magic(4)};
s = struct(field_name,values)
s.field_name

### Code:

field1 = 'field1';  value1 = zeros(1,15);
field2 = 'field2';  value2 = {'str1', 'str2'};
field3 = 'field3';  value3 = {pi/3, pi.^3};
field4 = 'field4';  value4 = {'text'};
s = struct(field1,value1,field2,value2,field3,value3,field4,value4);
s.field1
s.field2
s.field3
s.field4

s=struct([])

## 8. Unsigned Integer

Matlab supports variable arrays that of the unsigned integer data type. The variables can be defined as 8/16/32/64-bit unsigned integer depending on the size of the data to be stored in the variable.

### Code:

var_int8 = uint8(50) ; var_int16 = uint16(50); var_int32 = uint32(50); var_int64 = uint64(50);

## 9. Fixed point data type

Matlab SIMULINK blocks allow users to create models that use fixed-point datatypenumerical to represent parameter values and signals. The application of fixed-point data reduces memory consumption and improves the speed of code that is generated from a SIMULINK model.

var1 = fi(pi)

### Output:

Note: When the return value from an expression is not assigned to any variableexplicitly, a default variable ‘ans’ gets defined by the system and the return value of the expressions gets assigned to it. This default variable ‘ans’ is reusable throughout the code. The elements or their subsets from a multidimensional array and tall arrays are not editable in the Variables editor. In the Workspace browser or the Variables editor, double quotes need to be used surrounding the string value while editing any string type variable.

If an empty variable is created or variable gets empty value during run time, the variable will be assigned to a default value based on the data type such as:

For numeric array variable: ‘0’

For cell and structure array variable: ‘[]’

For categorical variable: ‘<undefined>’

# Matlab Global Variables

In MATLAB if various functions declare the name of a variable as global, in that case, these functions will utilize a single instance of the variable called global. If we make any change in the value of that variable, by changing it in any of the function, the change will be applicable to all the other functions using it as a global variable.

Functions have their variables called local variables. The scope of these variables is limited only to the scope of the function itself whereas the scope of the global variables extends to all the functions that call the global variable.

## Syntax:

1. global v1, v2, v3 ….vn is used to declare any variable as a global variable.
2. As it is evident from the syntax, we can set multiple variables as global in a single declaration.
3. If we need to clear a global variable, we can use the syntax “clear all” to clear all the global variables defined

## How set a Variable as Global in Matlab?

Let us now understand how to set a variable as global in MATLAB:

### Example 1:

In the first example, we will declare a global variable in the beginning and then will use it inside a function. The steps to be followed for this example are:

1. Declare a variable as global
2. Create a function
3. Call the global variable inside the function
4. Call the function to get the output and verify if the global variable is working as expected

### Code:

global x

[Declaring the global variable ‘x’]

x = 10;

[Assigning a value to the global variable]

Next, we will create a function that performs the multiplication of 2 integers. One of the inputs will be the global variable declared above.

function A()
global x
X = 6 * x;
X
end

[Please note that the above function has called the global variable ‘x’, and will hence utilize the value assigned to it by us; i.e. 10]

Now if we call the function ‘A’, then the output must be 6 * 10 = 60.

This is how our input and output will look like in the MATLAB command window:

### Input 1:

Declaring the global variable:

### Input 2:

Creating the function and calling the global variable declared in the above step:

### Input 3:

Calling the function ‘A’:

### Output:

As we can see in the Output, we have obtained products of 10 & 6 which is 60. Here, we have utilized our global variable defined outside the body of the function as one of the inputs.

Next, we will create another function and will utilize the same global variable ‘x’ created by us in the beginning.

## Example 2:

In this example, we will create a new function but will utilize the same global variable as we created for our first example. Here, we will not declare a global variable but will simply call it inside the body of our new function. This is a valid approach because we have already declared the variable ‘x’ as global at the beginning of our workspace. The steps to be followed for this example are:

1. Create a function
2. Call the global variable inside the function
3. Call the function to get the output and verify if the global variable is working as expected

### Code:

We will create a function that performs a division of 2 integers and will directly use the global variable declared in the first example as one of the inputs.

function B()
global x
Y = 80 / x;
Y

end
[Please note that the above function has called the global variable ‘x’ directly without declaring it in the beginning]

Now if we call the function ‘B’, then the output must be 80 / 10 = 8.

This is how our input and output will look like in the MATLAB command window:

### Input 1:

Creating the function ‘B’ and using the global variable declared in the beginning of the workspace:

### Input 2:

Calling the function ‘B’:

### Output:

As we can see in the OUTPUT, we have obtained the division of 80 & 10 which is 8. Here, we have utilized our global variable defined at the beginning of the workspace as one of the inputs.

Next, we will learn how to clear the global variables. For this, we will use the syntax “clear all”. Please keep in mind that, if we use the “clear all” syntax. we will no longer be able to use the global variable ‘x’ defined above in our functions.

## Example 3:

In this example, we will clear the global variable created by us. The steps to be followed for this example are:

1. Use “clear all” syntax
2. Call the global variable inside the function
3. Call the function to get the output and verify if the global variable is working as expected (it should not give any output, as we have cleared the global variable from our workspace)

### Code:

Now if we call the function ‘A’, then there must not be any output.

This is how our input and output will look like in the MATLAB command window:

Input 1:

Clearing the global variable created:

Input 2:

Calling the function ‘A’:

### Output:

As we can see, we are not getting any value as the output. This is because we do not have any value now for the global variable ‘x’