Loading data from .mat file and converting them to string array
15 views (last 30 days)
Show older comments
I need to create a .mat file in which I save a string array using the following two command lines (the original array could be much larger):
Grades={'CB 21'; 'CB 22'; 'CB 24'; 'CB 25'};
save GradNames.mat Grades
but when I try to read the data from it and asign them to the array GN by:
load ('GradNames.mat', 'GN')
MATLAB returns the warning:
Warning: Variable 'GN' not found.
In Save2Mat (line 5)
0 Comments
Accepted Answer
Les Beckham
on 7 Feb 2023
Edited: Les Beckham
on 7 Feb 2023
You only save one variable into the mat file and its name is Grades.
The syntax load('matfilename.mat', 'varname') tries to find a variable named varname in the matfile. Since your mat file doesn't contain a variable called GN, you get the error.
If you do load('GradNames.mat') you will see that your variable Grades will appear in the workspace and you can copy it to GN if you want to.
However, it is generally recommended to load mat files into a data structure so you won't accidentally overwrite an existing variable in your workspace (especially if you aren't sure what is inside the mat file.
To do this, use syntax like this: GN = load('GradNames.mat'). For example:
Grades={'CB 21'; 'CB 22'; 'CB 24'; 'CB 25'};
save('GradNames.mat', 'Grades');
clearvars % clear the workspace
GN = load('GradNames.mat');
whos % check what is in the workspace
GN
GN.Grades % now the original Grades cell array is a member of the GN struct
2 Comments
More Answers (1)
Walter Roberson
on 7 Feb 2023
load ('GradNames.mat', 'GN')
means that a variable named GN is to be looked for inside the file, and if it is found, loaded into the workspace. It does not take whatever variable is found in the file and assign it to GN . (Imagine the problems that syntax would have if there were more than one variable in the file.)
datastruct = load('GradNames.mat', 'Grades');
GN = datastruct.Grades;
See Also
Categories
Find more on Workspace Variables and MAT-Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!