How to process multiple dot mat file using for loop

Hello every one, please help me in solving this issue
I have thousands of mat files as shown in figure for sample. Each mat file contains a variable called ‘val’ which is 2 by 19000 matrices. What I need is to extract the first raw of ‘val’ of each dot mat file and save it by naming sequentially like “x1, x2, x3……..” Using for loop.
I have done for a single file successfully by the following algorithm
>> clear all
>> load('dist (1).mat')
>> x = val(1,:);
>> save('x1.mat', 'x')
I have attached some of the dot mat files
Thanks so much in advance for your help

답변 (1개)

David Fletcher
David Fletcher 2021년 5월 24일
Wouldn't it be better to extract what you want into a single matrix and then just save the one matrix with all the data rather than having thousands of separate files? Having said that, a basic framework for doing what you want is:
clear
numberOfFiles= %enter number of files;
for iter=1:numberOfFiles
fName=sprintf('dist (%d).mat',iter);
x=load(fName);
x=x.val(1,:);
fName=sprintf('x%d.mat',iter);
save(fName, 'x');
end

댓글 수: 5

Thank you so much Mr. Fletcher this worked perfectly and you saved my time. As additional how could I extract what I want into a single matrix and then save the one matrix with all the data as you said?
Assuming all the matrices are have the same number of columns, you can put everything into one matrix with each row being a separate data file
clear
numberOfFiles= %enter number of files;
for iter=1:numberOfFiles
fName=sprintf('dist (%d).mat',iter);
x=load(fName);
allData(iter,:)=x.val(1,:)
end
save('data.mat', 'allData.mat')
If the size of the matrices are not the same you would have to use a cell array rather than a matrix
Yared Daniel
Yared Daniel 2021년 5월 24일
편집: Yared Daniel 2021년 5월 24일
I got this error I think it is due the size of the matrices. how would use cell array sir?
Unable to perform assignment because the size of the left side is 1-by-19200 and
the size of the right side is 1-by-21600.
Error in AL_in (line 4)
allData(iter,:)=x.val(1,:)
clear
numberOfFiles= %enter number of files;
for iter=1:numberOfFiles
fName=sprintf('dist (%d).mat',iter);
x=load(fName);
allData{iter}=x.val(1,:)
end
save('data.mat', 'allData.mat')
I sincerely appreciate your help thank you so much

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2021년 5월 24일

댓글:

2021년 5월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by