How to write (partial)file names into a table?

조회 수: 4 (최근 30일)
Simone Speltoni
Simone Speltoni 2021년 5월 20일
댓글: Simone Speltoni 2021년 5월 20일
Hi, I have a list of .csv files, that I read through a loop and make some operations on, such as trapz. The code works fine, probably there are some smarter ways to do it, but anyway
clear all
close all
files = dir('*.csv')
N = length(files) ;
% loop for each file
fileNames = {files.name};
integ=zeros(N,4);
for m = 1:N
T = readtable(fileNames{m});
[numRows,numCols] = size(T);
cont=0;
tB= T(:,4); %consider specific columns of every .csv file
tA= T(:,3);
tC= T(:,5);
B=table2array(tB) %consider arrays
A=table2array(tA)
C=table2array(tC)
bvB=B(1,1); %consider base values
bvA=A(1,1);
bvC=C(1,1);
newB=B(:,1)-bvB; %subtract base value
newA=A(:,1)-bvA;
newC=C(:,1)-bvC;
f=numRows-1;
integ(m,1)=trapz(newB(1:f));
integ(m,2)=trapz(newA(1:f));
integ(m,3)=trapz(newC(1:f));
end
I would like to add, in the 4th column of the table integ, the ID of the actual .csv file on which the loop is running on, not the whole string, but just the increasing number between the _ _. For example, the files are
M_20210329-1318_116_l116.csv
M_20210329-1328_117_l117.csv
M_20210329-1337_118_l118.csv
and I would like to add 116, 117, 118 in the integ(m,4). I guess I'm having some trouble because fileNames is a cell, I used Id=cell2table(fileNames) to get a table with the names of the single files, but still I'm missing the goal. Is it possible? Thanks

채택된 답변

David Fletcher
David Fletcher 2021년 5월 20일
편집: David Fletcher 2021년 5월 20일
Try this - (I'm assuming you want to store the extracted chars as an actual number)
integ(m,4)=str2double(extractBetween(fileNames{m},'_l','_'))
This isn't exactly the same as you asked for, but it is conceptually easier (especially for me) to use the extractBetween function to cut the number out from between '_l' and the '_' at the end. If you specifically want the number between the two underscores you could resort to using regexp - maybe something like:
integ(m,4)=str2double(regexp(fileNames{m},'_(\d+)_','tokens','once'));
  댓글 수: 1
Simone Speltoni
Simone Speltoni 2021년 5월 20일
Thank you very much David, both solutions are useful!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by