MATLAB: Dicom pixel value matrix into CVS file

1ddicommatrix

I have 50 dicom files in one folder. i need to transfer pixel matrix of each image file into one common csv file and also the next image matrix must start from the next row in the same csv file. here is my code.
myFolder = ' ';
filePattern = fullfile(myFolder, '*.dcm');
image = dir(filePattern);
for k = 1:length(image)
baseFileName = image(k).name;
fullFileName = fullfile(myFolder, baseFileName);
I= dicomread(fullFileName);
rowImage = reshape(I, 1, []);
if k == 1
csvwrite('file.csv', rowImage, 'delimeter',',');
else
csvwrite('file.csv', rowImage, 'delimiter',',','-append');
end
end
my code is not doing the thing i want . Anyone who can help with this code would be appreciated.

Best Answer

Writing each dcm file to a separate column:
myFolder = '403498/New';
outfile = fullfile(myFolder, 'file.csv');
filePattern = fullfile(myFolder, '*.dcm');
dcmimage = dir(filePattern);
numfiles = length(dcmimage);
images = nan(1, numfiles);
for k = 1:numfiles
baseFileName = dcmimage(k).name;
fullFileName = fullfile(myFolder, baseFileName);
I = reshape(dicomread(fullFileName), [], 1);
numI = numel(I);
cursize = size(images,1);
if cursize < numI
images(end+1:numI,:) = nan;
elseif numI < cursize
I(end+1:cursize) = nan;
end
images(:,k) = I;
end
dlmwrite(outfile, images)
Because each file might be a different length, this pads with nan out to the longest file. It is possible to write out empty cells instead, but the file writing portion would be more work.
Note that it would be common for dcm files to have more than 1048576 elements, which is the maximum row limit for xlsx files. If you were planning and processing this csv file through excel or any tool uses excel to read csv files (such as xlsread()) then you are probably going to have problems.
I think you should be reconsidering writing the pixel values as text all into a common file.