passing character strings into functions
2 views (last 30 days)
Show older comments
I had a quick question on passing a character array into a function for example:
I have an array of image names and i want to iterate through them to edit them all in a certain way. I dont know what command to put in the load function below.
if true
picturenames = char('IMG_1562' 'IMG_1563' 'IMG_1564' 'IMG_1565');
for i=1:length(picturenames);
imread(% what would go here...);
% ill run my edits here
end
end
0 Comments
Accepted Answer
CS Researcher
on 2 May 2016
You can use a cell array:
picturnames = {'IMG_1562' 'IMG_1563' 'IMG_1564' 'IMG_1565'};
Pass picturnames to the function like you are and do
imread(picturenames{1,i});
0 Comments
More Answers (1)
Image Analyst
on 2 May 2016
See the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F for the best way(s).
In your case you have a character array, so you need to extract one row like this:
picturenames = char('IMG_1562', 'IMG_1563', 'IMG_1564', 'IMG_1565')
for k = 1 : size(picturenames, 1)
thisName = picturenames(k, :)
if exist(thisName, 'file')
imread(thisName);
else
message = sprintf('%s does not exist', thisName);
uiwait(warndlg(message));
end
end
However a more robust way is to use cell arrays which will allow the filenames to have different lengths.
picturenames = {'IMG_1562', 'IMG_1563', 'IMG_1564', 'IMG_1565'}
for k = 1 : length(picturenames)
thisName = picturenames{k}
if exist(thisName, 'file')
imread(thisName);
else
message = sprintf('%s does not exist', thisName);
uiwait(warndlg(message));
end
end
One thing I worry about is that you might want to add the extension to the filenames - it's always good to have one so the imread() function can automatically tell what kind of image format it is. And you can use dir() so that you don't have to check inside the loop if the file exists. Again, it's all in the FAQ.
0 Comments
See Also
Categories
Find more on Get Started with MATLAB 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!