What's wrong with my preallocation of images?

조회 수: 4 (최근 30일)
Iana Ladygina
Iana Ladygina 2019년 12월 20일
댓글: Walter Roberson 2019년 12월 30일
folders = dir("photos");
folders = string({folders.name});
folders = folders(~startsWith(folders,"."))
% Preallocate the structure crashImages
crashImages(length(folders)) = struct("Name",folders(end),"Images",cell(1));
for k = 1:length(folders)
photos = dir("photos\" + folders(k));
photos = string({photos.name});
photos = photos(~startsWith(photos,'.'));
% preallocate the cell array images
images = cell(length(photos),1);
for kk = 1:length(photos)
im = imread("photos\" + folders(k) + "\" + photos(kk));
images{kk} = im;
end
crashImages(k).Name = folders(k);
crashImages(k).Images = images;
clear images
end
crashImages
I get the error that the cell arrays in the Image field do not have the correct sizes. What could be the problem?
  댓글 수: 2
Catalytic
Catalytic 2019년 12월 20일
It is generally more informative to copy/paste your error messages (all of them) than to summarize them in your own words. That way, we can see for example what line of code was to blame.
Stephen23
Stephen23 2019년 12월 30일
편집: Stephen23 2019년 12월 30일
Simpler and more robust than using startsWith:
S = dir("photos");
folders = setdiff({S.name},{'.','..'});
Note that you can easily use the same structure that dir returns:
S = dir('photos');
S(ismember({S.name},{'.','..'})) = [];
for k = 1:numel(S)
...
S(k).image = images;
end
Also you should use fullfile rather than concatenating strings together.
"I get the error that the cell arrays in the Image field do not have the correct sizes. What could be the problem?"
If you don't show us the complete error message then we have to guess what the problem is.

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

답변 (1개)

Matt J
Matt J 2019년 12월 20일
편집: Matt J 2019년 12월 20일
Maybe you meant to have,
crashImages(length(folders)) = struct("Name",folders{end},"Images",cell{1});
  댓글 수: 4
Iana Ladygina
Iana Ladygina 2019년 12월 30일
Sorry, may be I don't understand it well, but how is fullfile() function related to the preallocation?
Walter Roberson
Walter Roberson 2019년 12월 30일
Your file reference is coming out wrong, so dir is returning empty, so length is 0, so images would be an empty cell. You then interpreted that as being the incorrect size.

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

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by