MATLAB: How to populate a csv file in a loop without overwriting it? I want to place each vector in a single row on each iteration. But the solution overwrites and creates a new csv each iteration.

.csv filecsvloop csv

% Specify the folder where the files live.
myDir = 'imgs';
% Get a list of all files in the folder with the desired file name pattern.
f = fullfile(myDir, '*.jpg'); % Change to whatever pattern you need.
theFiles = dir(f);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myDir, baseFileName);
imag = imread(fullFileName); %reads image
imag_gray = rgb2gray(imag); %turns image to grayscale
imag_28 = imresize(imag_gray, [28 28]); %resizes image
vector_imag = imag_28(:); %vectorizes the image
csvwrite('imgdata.csv', vector_imag); %writes vectorized image to csv file
end

Best Answer

Inside The Loop Don't Write To File And Populate A Matrix Instead.
vector_imag(:,k) = imag_28(:);
Then Write Everything To The File After The Loop
You will Have Better Performance As Well
Don't Forget To Preallocate Matrix Before Loop:
vector_imag = zeros(28^2, length(theFiles));