Problem with loading variables under the same names to Matlab

9 次查看(过去 30 天)
I use a .mat file generated by the software, hence by definition i cant change the settings of exportation. However, my problem is that the generated file saves the variables under the same name! (yes, you heard me right!) When i am trying to load the variables from the script it doesnt load the biggest array which i need and instead it loads whatever it feels comfortable with. I cannot sit here all day and load each variable clicking a mouse. Is there a way to separate variables saved under the same name? I would really appreciate your help.
With kind regards, Sholpan

回答(1 个)

Stephen23
Stephen23 2015-2-12
编辑:Stephen23 2015-2-12
Have you looked at the load documentation? If you load the .MAT data into a structure, then you can collect all of these together into a (non-scalar) structure.
First lets create a few .MAT files, all using the same variable name A:
>> A = [0];
>> save('temp1','A')
>> A = [Inf,-Inf,NaN];
>> save('temp2','A')
>> A = [1,2,3];
>> save('temp3','A')
Now run this code to load them all at once:
>> D = dir('temp*.mat');
>> S = cellfun(@load,{D.name});
Lets check the third file's value:
>> S(3).A
ans = [1,2,3]
Which is correct. We can also get that file's name with D(3).name.
This code assumes that every .MAT file contains exactly the same fields (but this can be any number of fields). If any .MAT file has different fields, then you can use load's optional arguments to specify what variables to load from the .MAT file:
S = cellfun(@(d)load(d,'A'),{D.name});
  3 个评论
Stephen23
Stephen23 2015-2-12
编辑:Stephen23 2015-2-12
How were these identically-named variables saved together in one .MAT file? I am guessing some external program created this, because it seems to be impossible to do this from inside MATLAB.
You might like to have a look at other answers about how to deal with this, or try a search on Answers . I can't recall seeing a solution to this.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by