How to insert image file name in listbox and show preview?

I want to populate my matlab gui listbox with my images file name. And once user clicks on the file name, they can preview the image. Why do I get this error - 'Cell contents assignment to a non-cell array object.'? So, all I have now is an empty listbox. I don't see anything wrong with my code.
% in openingFCN:
files = dir(fullfile(pwd,'Folder','*.jpg'));
for x = 1 : length(files)
handles.images{x} = imread(fullfile(pwd,'Folder',files(x).name));
end
set(handles.listbox1,'string',{files.name});
% in listbox1 Callback:
handles.output = hObject;
index = get(handles.listbox1,'value');
imshow(handles.images{index});
guidata(hObject, handles);

 Accepted Answer

Which line is giving you this error?
Possibly, this one:
handles.images{x} = imread(fullfile(pwd,'Folder',files(x).name));
which would indicate that handles.images already exists and is not a cell array.
In which case,
handles.images = cell(1, numel(files));
for x = 1 : numel(files)
%... rest of the code
should solve the problem.
It's a good idea to predeclare your arrays in matlab anyway (although for cell arrays it's not going to make much different to performance).

5 Comments

Thank you! for the code and explanation..solves my problem..
Preallocating cell arrays makes a big difference to performance, and certainly to memory usage: "For very large arrays, incrementally increasing the number of cells or the number of elements in a cell results in Out of Memory errors"
is there any other way to solve this?
handles.images{x} = imread(fullfile(pwd,'Folder',files(x).name));
now that I follow @Guillaume's solution, I'm having another error 'Conversion to double from cell is not possible.' when I wanna set buttondownfcn for my image in handles.images. I want to be able to click on the images in handles.images which will further show the image description with values from my database.
@saturday. The 'conversion to double from cell' error must be when you read the cell content so does not come from the line you've shown.
Please show the line responsible for the error.
@Stephen, of course resizing large cell arrays will have a major effect on memory / performance. On the other hand resizing a small cell array has a much smaller impact than resizing say a char array, since the only thing that is copied are the pointers to the cell contents rather than the content themselves.
@Guillaume, it's okay..i found another method to do what i want next..so everything's done now..thanks for your help..the code you gave earlier was very helpful..

Sign in to comment.

More Answers (0)

Asked:

on 15 May 2015

Commented:

on 15 May 2015

Community Treasure Hunt

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

Start Hunting!