How to concatenate variables in different matlab files?
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuesta aceptada
Image Analyst
el 24 de Sept. de 2012
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 comentarios
Image Analyst
el 24 de Sept. de 2012
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.
Más respuestas (2)
Aaditya Kalsi
el 24 de Sept. de 2012
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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!