passing character strings into functions

13 ビュー (過去 30 日間)
Cprogg
Cprogg 2016 年 5 月 2 日
回答済み: Image Analyst 2016 年 5 月 2 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by