imwrite with variable filename

3 views (last 30 days)
Hi,
I'm trying to call imwrite in a loop:
ori_dir = 'path/to/folder'
files = {'fi','le','na','me'};
for k = 1:length(files)
% do some operation on img %
write_dir = strcat(ori_dir, '/', files(k),'.tif');
imwrite(img, write_dir);
end
I'm getting the following error
Error using imwrite>parse_inputs (line 510)
A filename must be supplied.
Error in imwrite (line 418)
[data, map, filename, format, paramPairs] = parse_inputs(varargin{:});
write_dir contains a string to the correct path however. If I paste the string directly in imwrite, I don't have any issue, eg:
imwrite( img, 'path/to/folder/fi.tif')
does not raise an error.
I'm not quite sure what is wrong here. The variable files is a cell array with only strings in it.
Any help would be really appreciated!

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 30 Oct 2013
Correct this line
write_dir = strcat(ori_dir, '/', files{k},'.tif')
  3 Comments
Walter Roberson
Walter Roberson on 9 Apr 2016
bill jones comments
doesnt actually provide an answer.
Walter Roberson
Walter Roberson on 9 Apr 2016
bill jones:
The original line was
write_dir = strcat(ori_dir, '/', files(k),'.tif');
the new suggested line is
write_dir = strcat(ori_dir, '/', files{k},'.tif');
This is different. Notice that files(k) has been changed to files{k} . files is a cell array of strings, so files(k) is a 1 x 1 cell array that contains a string. When you strcat() something that contains a cell array of strings, the result is a cell array of strings, but imwrite() cannot handle a file name which is a cell array of strings. files{k} on the other hand is the string extracted from the cell array. That leaves you strcat() only strings, which gives a string result, and imwrite() can deal with that.

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!