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

1 次查看(过去 30 天)
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?

回答(1 个)

dpb
dpb 2017-7-9
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 个评论
yue ishida
yue ishida 2017-7-13
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 2017-7-13
编辑:dpb 2017-7-13
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by