How to concatenate variables in different matlab files?

18 次查看(过去 30 天)
I have two mat files with identical number of variables.
In file1.mat
Variables
Time [100X1] double
Force [100x1] double
In file2.mat
Variables
Time_1 [90X1] double
Force_1 [90x1] double
I would like to vertically concatenate these variables. The suffix '_1' is constant for all variables in one file, but changes from file to file.
Thanks

采纳的回答

Image Analyst
Image Analyst 2012-9-24
bothTimes = [Time; Time_1];
bothForces = [Force; Force_1];
By the way, you would make it simpler if all files just saved the same variable and called it Time. Then you could simply do
s1 = load(fullFIleName1);
s2 = load(fullFileName2);
bothTimes = [s1.Time; s2.Time];
bothForces = [s1.Force; s2.Force];
and your code would not have to worry about whether the name of the variable had a _1 or _2 or _3 in it.
You can use the fieldnames() function to find out the name of what's in your s1 or s2. But then you have to use dynamic fieldnames or just try every possibility if you're going to have numbers hard coded into the variable names.
  3 个评论
Image Analyst
Image Analyst 2012-9-24
Uh, yeah but in case you didn't notice that was what I was hoping you wouldn't do. Is there any reason why your other code MUST create variables with different names? Maybe you think it will make things easier down the line, but it doesn't. Like I said, the preferred way was to have the other function just save the mat files with all the variables in it having the same name. If you insist on doing it the hard way, then see Aaditya's method below which uses dynamic field names.
Prasanna Srisailan
Prasanna Srisailan 2012-10-5
The reason is, there is already existing data with different suffixes added to the variables in different files. So I have try out all possibilities to find the right match.

请先登录,再进行评论。

更多回答(2 个)

Aaditya Kalsi
Aaditya Kalsi 2012-9-24
You can do this quite simply:
% load initial data
filedata = load('file1.mat');
Time = filedata.Time;
Force = filedata.Force;
num_more_files = 2 % say i had two more mat-files
for i = 1:num_more_files
var_appended_str = ['_' num2str(i)];
filename = ['file' num2str(i) '.mat'];
filedata = load(filename);
Time = [Time; filedata.(sprintf(['Time' var_appended_str]))];
Force = [Force; filedata.(sprintf(['Force' var_appended_str]))];
end
This code has not been tested but you get the idea.
Hope this helps.

Walter Roberson
Walter Roberson 2012-9-24

类别

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