Clear Filters
Clear Filters

how to write the results from the code into the csv file format?

3 views (last 30 days)
Code below is producing the result including dates format and I usually use dlmwrite to write the results in csv format but in this case I am getting an error below: (What should I change so I can save the results)
Error using sprintf
Unable to convert 'duration' value to 'double'.
Error in dlmwrite (line 161)
str = sprintf(format,m(i,:));
Error in ploting_timeoverUy (line 30)
close all; clear all; clc;
projectdir = 'F:\3-PIV_Experimental_Data\Outlet_110\Data_LaserSheet_D\Data_PIV\5-AverageFilter_VelocitiesExtration\Point_Velocities\Uy';
files = dir( fullfile(projectdir, '*', '*.csv') );
filenames = fullfile({files.folder}, {});
num_files = length(filenames);
all_Uy = zeros(num_files,1);
all_time = zeros(num_files,1);
for i = 1:numel(files)
filename = filenames{i};
data = readmatrix(filename);
all_Uy(i) = data(1,2);
Location = 'F:\3-PIV_Experimental_Data\Outlet_110\Data_LaserSheet_D\Data_PIV\5-AverageFilter_VelocitiesExtration\Point_Velocities\Uy';
files = dir(Location);
dirFlags = [files.isdir];
subFolders = files(dirFlags);
subFolderNames = {subFolders(3:end).name}
for k = 1 : length(subFolderNames)
fprintf('Sub folder #%d = %s\n', k, subFolderNames{k});
dates = extractBetween(subFolderNames,"Run ",".");
dates = replace(dates,'-',':');
dates = duration(dates,"InputFormat","hh:mm:ss")
plot(dates,all_Uy, '-*');

Accepted Answer

Cris LaPierre
Cris LaPierre on 10 Mar 2022
I'd try using writematrix instead.
muhammad choudhry
muhammad choudhry on 10 Mar 2022
cheers, that worked and thanks for the explanation. I will remember that " all the matrix values has to be in the same datatype"
Image Analyst
Image Analyst on 10 Mar 2022
That's for dlmwrite and csvwrite(). For tables, each column can be different, or for max flexbility, you can use fprintf() like I showed below in my answer.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 10 Mar 2022
You could do it manually with fprintf():
fid = fopen(fileName, 'wt');
if fid == -1
warningMessage = sprintf('Error opening file for output:\n%s', fileName);
for k = 1 : length(all_Uy)
fprintf(fid, '%s, %f\n', dates(k), all_Uy(k));
I'm not sure about the dates format. You may have to make sure the dates value matches the format specifier. If it's a string, %s will work.

Community Treasure Hunt

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

Start Hunting!