passing character strings into functions

2 次查看(过去 30 天)
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

采纳的回答

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

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by