Search code examples
matlabcsvnested-loopsfile-handlingcell-array

how to save multiple Cell array values in one .csv file


I have been working on making a database which contains images and their preset values and other important parameters. But unfortunately, I'm not being able to save the initial data of say 10 images in one .csv file. I have made the code that runs fine with creating .csv file but saving the last value and overwriting all the previous values. I gave also once modified that is comment down in the code using sprintf but it make .csv file for every iteration separately. But i want to make one .csv file containing 7 column with all the respective values.

My code is below and output of my code is attached Output. Please someone guide me how to make single .csv file with 10 values for instance (could be increased to hundreds in final database) to save in 1 .csv file.

clc
clear all

myFolder = 'C:\Users\USER\Desktop\PixROIDirectory\PixelLabelData_1';
filePattern = fullfile(myFolder, '*.png'); % Change to whatever pattern you need
theFiles = dir(filePattern);

load('gTruthPIXDATA.mat','gTruth')
gTruth.LabelDefinitions;
for i=1:10
%gTruth.LabelData{i,1};

baseFileName = theFiles(i).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
imageArray = imread(fullFileName);
oUt = regionprops(imageArray,'BoundingBox');
Y = floor(oUt.BoundingBox);
X_axis = Y(1);
Y_axis = Y(2);
Width = Y(3);
Height = Y(4);

CLASS = gTruth.LabelDefinitions{1,1};
JPG = gTruth.DataSource.Source{i,1};
PNG = gTruth.LabelData{i,1};
OUTPUT = [JPG X_axis Y_axis Width Height CLASS PNG]

%     myFile = sprintf('value%d.csv',i);
%     csvwrite(myFile,OUTPUT);

end

Solution

  • Try fprintf (https://www.mathworks.com/help/matlab/ref/fprintf.html).

    You will need to open your output file to be written, then you can append lines to it through each iteration

    Simple example:

    A = [1:10];                   % made up a matrix of numbers
    fid = fopen('test.csv','w');  % open a blank csv and set as writable
    for i = 1:length(A)           % loop through the matrix
         fprintf(fid,'%i\n',A(i)); % print each integer, then a line break \n
    end
    fclose(fid);                   % close the file for writing