How to concatenate variables in different matlab files?
10 ビュー (過去 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
0 件のコメント
採用された回答
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
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.
その他の回答 (2 件)
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.
0 件のコメント
参考
カテゴリ
Help Center および File 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!