Problem using the results of the ls fxn
Show older comments
Hey All,
I'be been using the ls fxn to make my life easier. I've been expanding a script that I've been working on for a few days now (note recent question history :S ) and I've run into a small problem.
My original code:
filelist = ls('*.csv');
for j=1:size(filelist,1)
if strcmp(filename,strtrim(filelist(j,1:end)))
rowtoremove=j;
end
end
filelist(rowtoremove,:)=[];
So whats going on here? I'm trying to remove the original file I was working on that was in the same folder as a number of others from a list of those other files. Now this seems to work perfectly and I've been working with it for a bout a day now.
The problem came when I needed to exclude a series of files as well as the original. I originally tried something of this sort...
filelist = ls('*.csv');
for j=1:size(filelist,1)
if strcmp(filename,strtrim(filelist(j,1:end)))
rowtoremove=j;
end
if strfind(filelist(j,1:end),'long')
filelist(j,:)=[];
end
end
filelist(rowtoremove,:)=[];
As you might imagine this creates a large issue as I remove rows before they are evaluated and lowers the number of rows in the array/matrix so that the j counter overshoots the number of rows left.
I'm apparently a bit fatigued atm and not being my usual clever self. I originally thought I could fix this issue by counting backwards but it doesn't seem that matlab allows for that. Any ideas?
Thanks for your time! Karl
Accepted Answer
More Answers (1)
Walter Roberson
on 19 Jul 2011
0 votes
If you are removing rows by deleting them, then it is usually a good idea to work backwards, so that no row becomes movable until after you have finished with it.
2 Comments
Karl
on 19 Jul 2011
Sean de Wolski
on 19 Jul 2011
for j = maxj:-1:1
%do stuff
end
to run it backwards.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!