Kahibaro
Discord Login Register

3.1 Creating, Viewing, and Editing Variables

Creating Variables in MATLAB

In MATLAB you create variables simply by assigning a value to a name. You do this in the Command Window or in a script by using the assignment operator =. MATLAB creates the variable immediately when it evaluates the assignment.

For example, type in the Command Window:

matlab
x = 5

After you press Enter, MATLAB evaluates the right side, stores the value 5, and associates that value with the name x. MATLAB also displays the result because there is no semicolon at the end of the line.

You can create variables from many kinds of values, such as scalars, vectors, matrices, logical values, and strings. For example:

matlab
a = 3.14;
b = [1 2 3 4];
c = [1 2; 3 4];
name = "Alice";
flag = true;

In each of these assignments the variable is created or updated. The semicolon at the end of the line suppresses output in the Command Window, so the value is stored but not printed there.

MATLAB allows variable names that begin with a letter, followed by letters, digits, or underscores. Names are case sensitive, so data, Data, and DATA are three different variables.

When you assign a new value to an existing variable, MATLAB overwrites the old value. For example, if you run:

matlab
x = 10;
x = x + 1;

the variable x first stores 10, then it is updated to store 11.

If you use a variable name on the right side of an expression before MATLAB has created it, MATLAB issues an error telling you that the variable is undefined.

Viewing Variables in the Command Window

You can always see the current value of a variable by typing its name in the Command Window and pressing Enter. MATLAB then displays the content of that variable. For example, after:

matlab
A = [1 2 3; 4 5 6];

if you type:

matlab
A

MATLAB displays the matrix A in the Command Window.

To get a quick list of variables that currently exist in the workspace, you can use the who and whos commands. The who command displays the variable names, while whos also shows details such as size, type, and memory usage:

matlab
who
whos

These commands are useful when you want to confirm which variables have been created and what they look like at a high level, without opening any additional windows.

For larger variables, such as big matrices or long vectors, it is often not practical to display the entire contents in the Command Window. In that case you might want to look only at a part of the variable. For example:

matlab
A(1,:)
A(:,2)

shows a single row or column, which can be easier to read.

You can also use disp to show a variable without printing its name label:

matlab
disp(A)

This displays the value only, which can be convenient inside scripts and functions where you want cleaner output.

Using the Workspace Browser to View Variables

The Workspace browser gives you a graphical view of your variables. It usually appears on the right side of the MATLAB Desktop. Each row represents one variable and shows information such as its name, size, and class.

Whenever you create or modify a variable in the Command Window or in a script, the Workspace browser updates automatically. If you create:

matlab
x = 10;
y = rand(3,3);

you will see x and y listed in the Workspace browser. The size of x appears as 1x1 and the size of y appears as 3x3. You can use this view to quickly verify that your variables have the expected dimensions and types.

If you double click a variable in the Workspace browser, MATLAB opens it in a separate window for detailed inspection and editing. For numeric and logical arrays, this window looks similar to a spreadsheet.

You can sort variables in the Workspace browser by clicking on the column headers, for example by name or by size. This can help when you have many variables and you want to find particular ones quickly.

If your Workspace browser is not visible, you can restore it from the MATLAB Desktop menus. This lets you rely on a visual interface to understand what is currently in memory, in addition to the text commands.

Editing Variables in the Command Window

You can change the value of any variable directly in the Command Window by assigning to it again. For example, if x already exists:

matlab
x = x + 5;

modifies x by adding 5 to its current value. MATLAB immediately stores the new result and, unless you use a semicolon, prints it.

For arrays you can edit individual elements by assigning to specific indices. Suppose:

matlab
A = [1 2 3; 4 5 6];

You can change a single element:

matlab
A(2,3) = 99;

Now the element in row 2, column 3 of A is 99. The rest of the matrix remains unchanged.

You can also assign to whole rows or columns:

matlab
A(1,:) = [7 8 9];
A(:,2) = [0; 0];

The first line replaces the entire first row. The second line sets both elements of the second column to 0. The sizes must match, so MATLAB requires that the right side of the assignment fits the part of the array you are replacing.

If you try to assign a value that changes the shape in an incompatible way, MATLAB issues an error. For instance, you cannot replace a row of length 3 with a row of length 4 in a 2x3 matrix.

Sometimes you might want to expand a variable by assigning to a position that does not yet exist. For example:

matlab
v = [1 2 3];
v(5) = 10;

MATLAB automatically grows v to length 5, fills the missing element with 0, and sets the fifth element to 10. While this is convenient, repeatedly growing arrays in this way can slow down code, so it is better to avoid it inside performance critical parts of your programs.

You can also overwrite entire variables with values of a completely different shape and type:

matlab
x = 3;
x = "now a string";
x = [1 2; 3 4];

Each assignment replaces the previous value. MATLAB does not require you to declare variable types in advance.

Editing Variables with the Variable Editor

The Variable Editor provides an interactive way to view and edit variables, especially arrays and tables. You open it by double clicking a variable in the Workspace browser or by using the openvar command:

matlab
openvar("A")

When you open a numeric array, it appears as a grid of cells, similar to a spreadsheet. Each row and column corresponds to positions in the array. You can click into any cell, type a new number, and press Enter to change that element. MATLAB updates the variable immediately.

You can also select multiple cells and type a new value to change them together. For example, you might select a whole column and type 0 to set all selected entries to zero. If you paste values from outside sources, such as a spreadsheet, MATLAB tries to insert them into the selected region of the array.

If your array is large, the Variable Editor only shows a portion at a time. You can scroll vertically and horizontally to view different parts of the variable. The indices of the current view appear along the top and left edges, which helps you track which part you are editing.

For some data types, the Variable Editor provides additional features. For instance, for string arrays you can edit text directly in each cell. For logical arrays you can often toggle values between true and false. For tables, each column has a name that appears in the Variable Editor, and you can adjust entries of each column in a similar grid.

Any changes you make in the Variable Editor take effect in the current workspace. If you switch back to the Command Window and display the variable, you will see the updated values. The Workspace browser also updates its size information after edits.

If you close the Variable Editor window, your changes remain in memory as long as the variables stay in the workspace. If you clear the variables or end the session, those changes are lost unless you explicitly save the data to a file in a separate step.

Creating Variables from Existing Data

Often you will create new variables based on existing ones. This can be as simple as performing arithmetic on a variable, or as complex as extracting and transforming parts of arrays.

For example, given:

matlab
A = [1 2 3; 4 5 6];

you can create a new variable with a simple calculation:

matlab
B = 2 * A;

Now B stores a scaled version of A. The original variable A is unchanged. You can create many such derived variables to keep intermediate results, which can make code easier to read.

You can create variables that hold subsets of arrays. For instance:

matlab
row1 = A(1,:);
col2 = A(:,2);
sub = A(1:2,2:3);

Here row1 is the first row of A, col2 is the second column, and sub is a submatrix. These new variables let you work conveniently with specific parts of your data without altering the original variable.

It is also common to combine several variables into one new variable. For example:

matlab
x = [1 2 3];
y = [4 5 6];
C = [x y];

creates a new row vector C that places x and y side by side. You can then use C for further calculations.

When working interactively, it can be helpful to choose descriptive variable names that reflect how each one is created. For instance, instead of:

matlab
a = mean(data);
b = a + 2;

you might use:

matlab
meanValue = mean(data);
shiftedMean = meanValue + 2;

These names make it easier to remember the purpose of each variable when you return later or examine the workspace.

Renaming and Copying Variables

MATLAB does not have a direct command that renames a variable in place, but you can achieve the same effect by copying and then clearing the old variable if needed.

To rename a variable, copy its contents to a new variable name:

matlab
oldName = [1 2 3];
newName = oldName;

Now newName refers to the same data. If you no longer want oldName, you can remove it by clearing it from the workspace in a separate step.

Copying variables is a general technique. Any time you want a separate copy that you can modify independently, you assign one variable to another:

matlab
A = [1 2; 3 4];
B = A;       % B starts as a copy of A
B(1,1) = 99; % changes B only

After these commands, A keeps its original values, and only B reflects the change. This can be useful when you want to experiment with changes to your data without affecting the original version.

You can also copy variables using the Variable Editor. If you right click a variable in the Workspace browser, you can copy and then paste it under a new name, which gives you a second variable with identical content.

Being clear about which variables you intend to modify helps you avoid accidental changes. Copying before editing is a simple way to protect original data while still allowing you to explore different manipulations.

Important points to remember:
Variables are created automatically when you assign a value with = in the Command Window or in a script.
Use plain assignment or indexing to edit variables in the Command Window. Changing indices edits only specific elements.
The Workspace browser shows all current variables, and double clicking opens them in the Variable Editor for spreadsheet-like editing.
Any edits in the Variable Editor immediately change the variables in the workspace.
To make an independent copy, assign one variable to another. Changes to the new variable do not affect the original.

Views: 43

Comments

Please login to add a comment.

Don't have an account? Register now!