renaming variable loaded from a file

47 ビュー (過去 30 日間)
Reza S
Reza S 2015 年 3 月 6 日
編集済み: Stephen23 2022 年 2 月 22 日
Hello, I have 4 .mat files including tens of variables of the same name. How I can rename the variables after loading each file in a new script file. I have read similar link but didn't work well.
Thanks

採用された回答

Star Strider
Star Strider 2015 年 3 月 6 日
Use either the load or matfile functions with an output argument. The structure format can keep the variable names separate.
For instance, if you have variable names ‘x’, ‘y’, and ‘z’ in each .mat file, you can load them all into your workspace without ambiguity. If your .mat files are named A.mat and B.mat, load them as:
A = load('A.mat');
B = load('B.mat');
then:
A.x % ‘x’ from A.mat
B.x % ‘x’ from B.mat
and so forth for the rest of them. You have to refer to them as such in the rest of your code, but they will be uniquely identified that way.
  3 件のコメント
Stephen23
Stephen23 2015 年 3 月 6 日
Star Strider
Star Strider 2015 年 3 月 6 日
My pleasure!

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

その他の回答 (1 件)

Mingyang Sun
Mingyang Sun 2022 年 2 月 22 日
編集済み: Mingyang Sun 2022 年 2 月 22 日
use the command:
newname = struct2cell(load(filename)); newname=newname{1};
you don't even need to know the original variable name!
  1 件のコメント
Stephen23
Stephen23 2022 年 2 月 22 日
編集済み: Stephen23 2022 年 2 月 22 日
That may be useful in the case of exactly one variable per file and very badly designed data (e.g. the variable is named the same as the file, or something similar), in which case the code should at least confirm that assumption:
C = struct2cell(load(filename));
assert(isscalar(C),'file must contain one variable only')
D = C{1};
However I would not recommend that approach as a solution to the original question ".. including tens of variables of the same name" because then you lose very important meta-information about those tens of variables (i.e. the variable names). For the original quetsion a much better approach would be to concatenate the imported data into one structure array, for example:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = load(F);
end
A = [S.data] % <--- one structure array, with the original names of the variables.

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

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by