필터 지우기
필터 지우기

How to concatenate variables in different matlab files?

조회 수: 19 (최근 30일)
Prasanna Srisailan
Prasanna Srisailan 2012년 9월 24일
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