MATLAB Answers

Finding substring based on another substring

5 views (last 30 days)
Derek Handwerk
Derek Handwerk on 28 Mar 2019
Edited: Image Analyst on 29 Mar 2019
I have a bunch of data files and can get all of their names via
D = dir('*.mat');
Each name has a couple of numbers in it in the format '*num1_###*num2_###*.mat' where ### is the actual number.
I can set num1 equal to some value, say 1.7, and then get all assotiated files i.e.
D = dir('*num1_1.7*)
essentially getting a row of num2 files for num1 = 1.7 if you think of num1 and num2 making a grid of values.
What is the most efficient way to get files along the diagonal? I.e. where num1 is equal to num2, but the values aren't known a priori.
For example, if I have the files
num1_1_num2_1.mat num1_2_num2_1.mat num1_3_num2_1.mat
num1_1_num2_2.mat num1_2_num2_2.mat num1_3_num2_2.mat
num1_1_num2_2.mat num1_2_num2_3.mat num1_3_num2_3.mat
from dir(), how can I extract
num1_1_num2_1.mat, num1_2_num2_2.mat, num1_3_num2_3.mat?

Accepted Answer

Stephen on 28 Mar 2019
Edited: Stephen on 28 Mar 2019
"What is the most efficient way to get files along the diagonal?"
Probably something like this is about as efficient as you can get with MATLAB:
S = dir('*.mat');
N = {};
M = sscanf([N{:}],'num1_%d_num2_%d.mat',[2,Inf])
Z = N(M(1,:)==M(2,:))

More Answers (0)





Community Treasure Hunt

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

Start Hunting!