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

15 ビュー (過去 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'}
  2 件のコメント
Saeid
Saeid 2023 年 2 月 7 日
Thank you, Les.
Les Beckham
Les Beckham 2023 年 2 月 8 日
You are quite welcome. Glad I could help.

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeWorkspace 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