Pull same column of cell from same variable, different .mat files

1 view (last 30 days)
Hi. I want to ask about my problem.
I have 30 .mat files. from results1.mat, results2.mat, results3.mat, until results30.mat. I want to pull same column from same cell but in different files, and put them together in a cell. For example, I want to pull column 2 of cell A in results1.mat and put in 1st column of cell, for results2.mat in 2nd column of cell, and so on until results30.mat. Can we do it in loop too?

Answers (1)

dpb
dpb on 9 Jul 2017
d=dir('results*.mat); % get the list of .mat files qualifying...
N=length(d); % how many files are there...
nCol=3; % the desired column (3 for example, change at will)
matobj=matfile(d(1).name); % make matfile object for first file
nRow=size(matobj.results,1); % number rows in file results variable
newmat=zeros(nRow,N); % preallocate newmat to hold all columns
newmat(:,1)=matobj.results(:,nCol); % save first column
clear matobj % done with the object now have data
for i=2:length(d) % iterate over the rest files found
matobj=matfile(d(i).name); % make matfile object each file in turn
newmat(:,i)=matobj.results(:,nCol); % each column in turn from the file
clear matobj % done with the object now have data
end
save newmat newmat % save the newmat array in newmat.mat file
Change variable names as desired, of course. The above assumes each file RESULTSn.MAT was saved from a variable named 'results'; if that's not correct, fix up the script to use the proper name.
doc matfile % for details
has section in example showing how to query the variable name(s) and use dynamic names it need be.
Also, the above presumes and requires that each vector is the same length in order to be able to concatenate into a double array.
  2 Comments
yue ishida
yue ishida on 13 Jul 2017
I have this problem.
Index exceeds matrix dimensions.
Error in extractvar (line 6) matobj=matfile(d(1).name); % make matfile object for first file
Do you know how to handle this?
dpb
dpb on 13 Jul 2017
Edited: dpb on 13 Jul 2017
What does
whos d
return?
That error implies there were no files found on the directory search if the first entry exceeds the array size.

Sign in to comment.

Categories

Find more on Entering Commands in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!