Azzera filtri
Azzera filtri

passing character strings into functions

9 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

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

Più risposte (1)

Image Analyst
Image Analyst il 2 Mag 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.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by