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

2 ビュー (過去 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 Center および File ExchangeData Distribution Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by