Clear Filters
Clear Filters

passing character strings into functions

8 views (last 30 days)
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

Accepted Answer

CS Researcher
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});

More Answers (1)

Image Analyst
Image Analyst on 2 May 2016
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.

Categories

Find more on Characters and Strings 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!