MATLAB Answers

Comparing strings of different lengths.

87 views (last 30 days)
Michiah Ruby
Michiah Ruby on 31 Oct 2020
Answered: Mara on 31 Oct 2020
I am trying to compare two filenames. I've assigned the filenames to varialbles, and I'm trying to compare the file names, if they match i need to perform some functions, if they do not match i need to skip.
Here's my code. It's inefficient, but It does what I need right now and I don't have time to go back and make it better.
clc;
clear all;
file = uigetdir;
contents = dir(file);
Data = fullfile(file,'Data')
for i = 1:length(contents)
[null,fName,fExt] = fileparts(contents(i).name);
L = strlength(fName);
G = L>10;
if G == 1
switch lower(fExt)
case '.txt'
samplefile = readcell(fName);
disp('1')
file2 = fullfile(Data,'*.txt');
specontents = dir(file2);
SampleID = cell2mat(samplefile(7,1))
for k = 1:length(specontents)
[null, fName1, fExt1] = fileparts(specontents(k).name);
specimenfile = readcell(fName1);
SpecID = cell2mat(specimenfile(3,2))
if SampleID == SpecID
disp('yes')
else
continue
end
% if sample ID in sample file == sample ID in specimen file
%disp(test)
end
%if samplefile <= length(samplefile)
%samplefile = readcell(fName)
%SampleID = cell2mat(samplefile(7,1))
% disp(speciminfile)
disp('YAY')
continue
end
else
disp('toss')
end
%disp('end')
end
disp('end')

Answers (1)

Mara
Mara on 31 Oct 2020
So is your question how to shorten your code? Maybe try this statement
if strcmp(filename1, filename2)
% Whatever you want it to perform if they are identical
end
Otherwise, if you do not look for completely identical filenames, there is the function contains().

Community Treasure Hunt

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

Start Hunting!