MATLAB's GUI allows us to save variables in the workspace to .mat
files to access later, and to load said files back into the workspace.
These features can be used to save on computation time and/or cost, if the information stored in the variables is time consuming to produce.
As we might expect, we can save any variable in the workspace to a variable file using the save
command.
This command works differently to other function calls that you've seen so far.
To use save
, we type save <filename> v1 v2 ...
where:
<filename>
is the name of the file we want to save the variables to, input as a string!v1 v2 ...
is a list of all the variables in the workspace that we want to include in the saved file.So for example...
mu0 = 4*pi*1e-7;
useful_vector = [1; 4; 9; 16; 25];
fun_matrix = magic(5); %the magic command creates a magic square and stores it in a matrix.
save "exampleSave" mu0 useful_vector fun_matrix
You should notice that, after executing the save command, a new file appears in the current directory panel of the GUI.
If we were to then start a new MATLAB session and want these variables back, we can then load
them from this file.
The load
command has similar syntax to save
, except we don't need to provide it with any variable names, only the filename (as a string).
clear; %remove the variables from the workspace to illustrate that we can re-load them!
load "exampleSave"
fprintf('To prove that the values really have reloaded after a clear:\n')
disp(mu0)
disp(useful_vector)
disp(fun_matrix)
Notice how the variables reappear in the current workspace with the same variable names as when we saved them.
This leads to a warning: the load
command will overwrite the value of variables that are already stored in the workspace if they share the same name!
Before we look at advanced techniques for isolating parts of arrays, we should first explore how we can access the individual entries in an array. The entries of an array can be accessed using indices to specify the position in the array of the value we want to extract. We need one index per dimension of the array, and indices range from 1 to the maximum length in that dimension of the array.
A = rand(3,5); %3-by-5 matrix with random entries
disp(A)
fprintf('The element at position (1,1) of the array is %.5f \n', A(1,1))
The syntax for accessing one entry in an array is to use the variable name followed by braces ( )
containing the indices.
In this case, our array A
is 2-dimensional (being a $3\times5$ array/matrix) and so we must use two indices to specify the value we want to find.
Vectors are 1-dimensonal arrays, so we only need to use a single index to specify which entry we want to look at:
v = rand(5,1); %column vector of length 5
disp(v)
fprintf('The element at position (3) of the vector is %.5f \n', v(3))
Now that we can access parts of an array, we can also assign them values and change the entries in the array directly.
This is done by isolating an element of an array, then using the =
operation to assign it a new value.
A = rand(3,5);
some_number_I_picked_for_an_example = 1e-1;
disp(A)
%change the (2,3) element of A to be -1
A(2,3) = -1;
%change the (3,5) element of A to be the value stored in the variable "some_number_I_picked_for_an_example"
A(3,5) = some_number_I_picked_for_an_example;
fprintf('A now looks like:\n')
disp(A)
In the previous lesson we dealt with defining arrays and performing operations on them. Here we look at more advanced techniques for working with arrays; in particular how we can isolate parts of an array and the in-built functions available to us when performing calculations with them.
There are some functions in MATLAB that allow us to extract parts of matrices quickly.
diag
is one of these functions (yes, the same diag
as in the previous lesson); when we give it a matrix argument it returns a vector that contains the diagonal entries of the matrix.
There are also the functions triu
and tril
which extract the upper and lower triangular parts of a matrix (respectively).
Of course, we may not only be interested in the diagonal or triangular parts of an array, but instead might be looking for a "sub-block" of a matrix or some important components of a vector. In these cases, we can use a technique called index slicing to aid us. This technique allows us to extract multiple entries at once, and also allows us to assign them at once too!
To "slice" an array, we use a colon (:
) when we try to access the values stored in an array.
A = rand(5,5);
disp(A)
fprintf('Extract the first row of A:\n')
A_first_row = A(1,:); %(1,:) means "take row 1, and all the columns"
disp(A_first_row)
fprintf('Extract the 3rd column of A:\n')
A_third_col = A(:,3); %(:,3) means "take all the rows, and column 3"
disp(A_third_col)
fprintf('Extract the 3-by-3 submatrix of A formed by the centre 9 entries\n')
A_centre_block = A(2:4,2:4); %(2:4,2:4) means "take rows 2-4, and columns 2-4"
disp(A_centre_block)
We can assign values to subsets of arrays by using =
.
You must assign an array of values of the same shape/size as the subset you are extracting, or provide a single scalar value.
If you provide the latter, every value you extract will be set to that scalar value.
Otherwise, you will simply insert the new array into the subset that you extracted.
fprintf('Set the centre 3-by-3 block of A to be 1 \n')
A(2:4,2:4) = ones(3,3); %"take rows 2-4 and columns 2-4 and set them to be a 3-by-3 matrix of ones"
disp(A)
fprintf('Set every value in the 2nd column of A to be 4.5 \n')
A(:,2) = 4.5; %"take all the rows and the second column and set them to be 4.5"
disp(A)
"But wait!", I hear you cry,
"What if I want to extract the final entry of an array, but don't know the size of the array?"
For this you can use the keyword end
when slicing.
MATLAB interprets this as "the value of the last index in this dimension of the array" when you try to extract values this way.
fprintf('Extract the final entry of the 3rd column of A: \n')
disp(A(end,3))
fprintf('Extract everything up to the penultimate value of row 4 of A: \n')
disp(A(4,1:end-1))
Notice that if you try to access part of an array that doesn't exist, for example index 5 of a vector of length 4, or index 0 of anything, you will get an "(array index) out of bounds" error:
v = ones(1,6); %length 6 row vector
v(7)
With the information above in mind, you can quickly realise that MATLAB will slice when you put vectors where you would normally place indices when extracting parts of an array. For example, we could extract all the even-index-elements of a vector:
v = rand(1,10); %random row vector of length 10
disp(v)
even_indexes = 2:2:length(v);
fprintf('Even-indexed values of v: \n')
disp(v(even_indexes))
Or we could pick out a selection of points from a matrix that we so happened to want:
A = rand(5,5);
disp(A)
row_inds = [2 4 5];
col_inds = [1 4];
fprintf('Our selection of indices gives us the values: \n')
disp(A(row_inds, col_inds))
Notice how even though our slices don't correspond to a continuous (or connected) subsection of our array, the extracted values still come out as a single "block".