Loading data from .mat file and converting them to string array

조회 수: 16 (최근 30일)
Saeid
Saeid 2023년 2월 7일
댓글: Les Beckham 2023년 2월 8일
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)

채택된 답변

Les Beckham
Les Beckham 2023년 2월 7일
편집: Les Beckham 2023년 2월 7일
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
Name Size Bytes Class Attributes GN 1x1 624 struct
GN
GN = struct with fields:
Grades: {4×1 cell}
GN.Grades % now the original Grades cell array is a member of the GN struct
ans = 4×1 cell array
{'CB 21'} {'CB 22'} {'CB 24'} {'CB 25'}

추가 답변 (1개)

Walter Roberson
Walter Roberson 2023년 2월 7일
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;

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by