Error in unziping files loop

2 views (last 30 days)
Oktavian Jason
Oktavian Jason on 19 Feb 2020
Edited: Stephen23 on 19 Feb 2020
Hello,
I want to create a code that
  1. Choose a folder
  2. Unzip .zip in that folder
  3. Delete some files with specific size
Below is my code.
files = fullfile(matlabroot, '\toolbox');
if ~exist(files, 'dir')
files = matlabroot;
end
uiwait(msgbox('Pick a folder on the next window that will come up.'));
selpath = uigetdir(files);
if selpath == 0
return;
end
projectdir = selpath;
dinfo = dir( fullfile( projectdir, '**', '*.zip') ); %find all .zip underneath the projectdir.
%then
for K = 1 : length(dinfo)
unzip( dinfo(K).name, dinfo(K).folder );
end
files = dir(projectdir);
deletedfiles = 0;
for itr = 1:length(files)
if files(itr).bytes<200000 && ~files(itr).isdir
files.name
delete(fullfile(files(itr).folder, files(itr).name))
deletedfiles=deletedfiles+1;
end
end
deletedfiles
But I got an error in the unzipping part.
>> cobacoba
Index exceeds matrix dimensions.
Error in cobacoba (line 14)
unzip( dinfo(K).name, dinfo(K).folder );
Any ideas what should I do?
  1 Comment
Walter Roberson
Walter Roberson on 19 Feb 2020
Check your variables. You might have a variable named unzip

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 19 Feb 2020
Edited: Stephen23 on 19 Feb 2020
You need to include the path in the filenames otherwise MATKAB does not know where to find those files, e.g.:
unzip(fullfile(dinfo(K).folder,dinfo(K).name),...);
You should also use numel, not length:
for K = 1:numel(dinfo)
I would regard any code that uses length as inherently buggy. This is a good example. Read the dir and length documentation and then think of what length returns when no files are returned by dir. Test it yourself.
Instead of buggy length you should use numel or size (requesting a specific dimension).
"Any ideas what should I do?"
Use whos and which to check if you have a variable defined named unzip.
  2 Comments
Walter Roberson
Walter Roberson on 19 Feb 2020
dir always returns a struct vector, never a 2d array. length is well defined for it. If no files are found then length will be empty and the loop body would not execute. There is no problem using length in this context.
Stephen23
Stephen23 on 19 Feb 2020
"If no files are found then length will be empty and the loop body would not execute."
Only because of an ugly special case in the length definition. Ugly special cases are bugs in waiting.

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!