0

I am retrieving file names of Images in a array as:

image_files = dir(strcat(dir_path, '\*' , img_extension));
s = image_files(j).name

Now I need to save names of images files in a file, but first I need to concatenate all the image names in a single matrix,

M = [M, s]

However since s is a character array, all the characters of file names will be treated as separate columns where as I need to treat a single file name as a single entity in M.

Is there any work around?

3
  • Try this maybe - {image_files.name}. It produces a cell array, if you are okay with it. Commented Mar 25, 2014 at 8:05
  • @Divakar then i wont be able to write this matrix, M, to a text file using dlmwrite() function.... is there any other way to write M to a text file even if it contains cell array elements.... thanks Commented Mar 25, 2014 at 8:07
  • 1
    dlmwrite doesn't support strings, only numeric data (the fact that it apparently happens to work with char arrays is an undocumented feature) - you'd be far better off using a cell array of strings. Commented Mar 25, 2014 at 9:39

1 Answer 1

1

Try this for PNG files in the working directory -

%%// Parameters
img_extension = '.png';
dir_path = pwd;
textfile = 'myFile.csv';

image_files = dir(strcat(dir_path,filesep,'*',img_extension));
x = {image_files.name};

fid=fopen(textfile,'wt');
[rows,cols]=size(x);
for i=1:rows
    %fprintf(fid,'%s,',x{i,1:end-1}); %%// Use comma separated file names
    fprintf(fid,'%s\n',x{i,1:end-1}); %%// Use newline separated file names
    fprintf(fid,'%s\n',x{i,end});
end
fclose(fid);

Edit 1: If you still need a char matrix or char arrays of the file names, choose from one of the following three outputs -

x = {image_files.name};
char_matrix1 = char(x{:}) %%// Create a MxN char matrix
char_array1  = strjoin(x,',') %%// Create a Mx1 char matrix separated by commas between filenames
char_array2  = strjoin(x,' ') %%// Create a Mx1 char matrix separated by spaces between filenames

Note : strjoin is available in the recent MATLAB version and on MATLAB file-exchange here.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Divakar, it seems a good solution , however not applicable in my scenario, thanks...
@Zohaib Try the Edit 1.
Just use filesep (or fullfile) to construct platform-independent paths, not that nasty if-else setup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.