필터 지우기
필터 지우기

Deleting certain elements from an array without looping

조회 수: 9 (최근 30일)
Teshan Rezel
Teshan Rezel 2021년 11월 8일
답변: Rik 2021년 11월 8일
Hi folks,
I have a cell array containing all the file names in a subfolder. I want to remove the filenames that are not 21 characters in length.
I have tried:
fileNames(length(fileNames(:)) ~= 21) = [];
but this only deletes one entry each time I run it, and not the correct ones eather!
May I please ask where I've gone wrong and how to fix it?
full code:
subFolders = dir(sourcePath);
subFolders = subFolders([subFolders(:).isdir]);
subFolders = subFolders(~ismember({subFolders(:).name},{'.','..'}));
fileNum = numel(subFolders);
folderDir = fullfile(subFolders(i).folder, subFolders(i).name);
folderDir = dir(folderDir);
folderDir = folderDir(~ismember({folderDir(:).name},{'.','..'}));
fileNames = {folderDir.name};
Thanks!
  댓글 수: 3
Chunru
Chunru 2021년 11월 8일
Can you provide a small part of fileNames so we know what it looks like?
Teshan Rezel
Teshan Rezel 2021년 11월 8일
@Rik apologies, I'll ammend my question to include this!

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 2021년 11월 8일
The code Chunru wrote will work, but I have a few suggestions.
Instead of using length, you should consider using numel as a habit. In this case dir will alway provide you with vectors, but there is no situation I know of where length is a better choice than either numel or size. I have never seen a non-contrived example where max(size(A)) was actually the intended behavior.
I would also like to point you to the legacy syntax of cellfun, which is the main (or only) situation where cellfun is faster than a loop:
fileNames = {'ThisIsADummyFile', '012345678901234567891'}
fileNames = 1×2 cell array
{'ThisIsADummyFile'} {'012345678901234567891'}
idx = cellfun('prodofsize', fileNames)~=21
idx = 1×2 logical array
1 0
fileNames(idx) =[]
fileNames = 1×1 cell array
{'012345678901234567891'}
You can also use idx to remove elements of the struct that dir returned.

추가 답변 (1개)

Chunru
Chunru 2021년 11월 8일
fileNames = {'ThisIsADummyFile', '012345678901234567891'}
fileNames = 1×2 cell array
{'ThisIsADummyFile'} {'012345678901234567891'}
idx = cellfun(@(x) length(x)~=21, fileNames)
idx = 1×2 logical array
1 0
fileNames(idx) =[]
fileNames = 1×1 cell array
{'012345678901234567891'}

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by