Merge vertically columns of many files

1 view (last 30 days)
Hi everyone,
I am trying to merge the columns from many arrays. The files I have are named (i)_MID.mat and contain five variables: N, P1, P2, R1, R2. Each of them have 3 columns and 10 rows. I would like to create a large vertically merged array of the N variables of all .mat files I have, ending with a 260 x 3 array, naming RT, Hit, Stim, to the columns of this array. I am working with this:
% Number of files to merge.
subjects = 26;
x=[]; % start w/ an empty array
for i=1:subjects
files = [num2str(i) '_MID.mat'];
x= vertcat(load(files));
end
savename = 'mergedarray';
save(savedname ,'x');
However, the file generated contains an array of 26x5 and in each cell has a 10x3 array. I want to generate an array of 260x3 for each condition, ideally (named as N_merged, P1_merged, etc). If this is not possible, an array of 260x15 (what I intended in the code above). Can you point me what I am doing wrong in this approach to achieve the goal. I attached 3 examples of the data, in case is necessary, as well as the output I am getting so far. Hopefully my explanation makes sense.
Many thanks

Accepted Answer

Sayam Ganguly
Sayam Ganguly on 17 Jul 2017
Hi, I understand that you are trying to vertically concatenate each of the variables(10X3 arrays) into separate arrays with dimension 260X3. You also want to add an header to indicate the name of the rows. I would like to suggest an approach that should help you achieve this. Here's the code below -
subjects = 26;
header = {'RT' 'Hit' 'Stim'};
mergeddata = zeros(0,3);
for ii=1:subjects
files = [num2str(ii) '_MID.mat'];
load(files);
mergeddata = vertcat(mergeddata,data_N);
end
mergeddata = [header;num2cell(mergeddata)];
savedname = 'mergedsubjects.mat';
save (savedname, 'mergeddata');
I have done this for the first variable only(i.e. data_N). Following the same approach you should be able to do this for others as well. In your code one thing that I noticed is that you are using 'vertcat' in an incorrect way. The correct way would be -
mergeddata = vertcat(mergeddata,neutral(jj));
Also I'm not sure why you are using the second for loop. Hope this helps!
  1 Comment
Ramiro Rea
Ramiro Rea on 17 Jul 2017
Edited: Ramiro Rea on 17 Jul 2017
Thank you very much, this solved the issue! I removed the second part to avoid confusions to other users.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!