Indexing in a loop using fileparts

3 ビュー (過去 30 日間)
James
James 2024 年 9 月 17 日
コメント済み: James 2024 年 9 月 17 日
Hello,
My filenames have the timestamp in them like this: X000_104520 where the #'s after the underscore are the HH:MM:SS
I wanted to loop through the files and take only the timestamp part and save it to a table or an array.
Here is my code that I'm having some issues with the indexing of the timestamp value (TS). Any help on this is appreciated, Thank you:
fileName = dir([pwd,'\*.txt']);
for n = 1:numel(fileName)
S=6;
[~,TS(n,:)]=fileparts(fileName(n).name);
L=length(TS(n,:));
TS(n,:)=TS(n,:)(L-(S-1):L); %Not able to properly index here
Results{n} = table(TS, 'VariableNames',{sprintf('File_%d',n)});
end
Results{:}
The filenames are, as I'm not able to upload the files due to Mathworks limit?
X000_104520.txt
X001_122004.txt
X002_034536.txt

採用された回答

Jatin
Jatin 2024 年 9 月 17 日
編集済み: Jatin 2024 年 9 月 17 日
Hi @James,
The error you're encountering is due to MATLAB not interpreting the chain of indexing, which is why attempting "TS(n,:)(L-(S-1):L)" results in an "Invalid array indexing" error. Here's a simplified version of the code that will give you the desired results.
fileName = dir([pwd,'/*.txt']); % Get all .txt files in the current directory
TS = strings(numel(fileName), 1); % Pre-allocate an array of strings for timestamps
for n = 1:numel(fileName)
[~, name] = fileparts(fileName(n).name); % Extract filename without extension
TS(n) = name(end-5:end); % Extract the last 6 characters for the timestamp
end
% Convert to a table and display results
Results = table(TS, 'VariableNames', {'Timestamp'});
disp(Results);
If you want to know more about the MATLAB's capacity of chained indexing, read this MATLAB Answer post:
Hope this helps!
  1 件のコメント
James
James 2024 年 9 月 17 日
Thank you. This works great!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWeb Services についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by