Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
82 lines (65 sloc) 2.47 KB
%DataGen Generate sample data in various formats
%
% Output:
% data.csv ...... comma-separated file
% data_tab.txt .. tab-separated file
% data.txt ...... tab-separated file, with header
% data.xls ...... Excel file
% data.mat ...... Matlab file
%
% ThH, Sept-2016
% Ver 1.2
%***********************************************
%% Set the parameters for a noisy sine-wave:
% Note that I set all the required values at the beginning of the script.
rate = 50; % [Hz]
freq = 2; % [Hz]
duration =4; % [sec]
amp = 5;
delta = deg2rad(90); % Phaseshift [deg]
%% Generate the data:
% Use variables, and DO NOT hardcode values. Using variables makes the code
% easier to read.
dt = 1/rate;
t = 0:dt:duration;
data = amp * sin(2*pi*freq*t + delta) + randn(size(t));
dataMat = [t', data'];
%Show how to display formatted data
outTxt = sprintf('The first time-sample is %5.3f, and the first data-value is %5.3f .', t(1), data(1));
disp(outTxt);
%% Write them to different files:
%% Comma-separated file:
outFile = 'data.csv';
dlmwrite(outFile, dataMat, ',');
% If you generate a new file, ALWAYS tell the user the name of the file
% that has been generated, and where in the path this file is located.
% Using a variable for the name of the out-file not only makes the code
% clearer, it also makes it possible to show the user which file has been
% generated.
disp([outFile ' has been generated in ' pwd]);
%% Tab-separated file:
outFile2 = 'data_tab.txt';
dlmwrite(outFile2, dataMat, '\t');
disp([outFile2 ' has been generated in ' pwd]);
% Tab-delimited file with header
outFile3 = 'data.txt';
fh = fopen(outFile3, 'w');
fprintf(fh, '%s\n', 'This file was generated on Aug 08, 2014.');
fprintf(fh, '%s%d%s\n\n', 'Sampling rate: ', rate, ' [Hz]');
fclose(fh);
dlmwrite(outFile3, dataMat, '-append', 'delimiter', '\t');
disp([outFile3 ' has been generated in ' pwd]);
%% Excel file:
% Requires that MS Excel is installed, if you want to generate binary Excel
% files. Note that the decimal values may be indicate by a "," instead of a
% ".", depending on the Windows Region settings!
outFileXLS = 'data.xls';
xlswrite(outFileXLS, dataMat);
disp([outFileXLS ' has been generated in ' pwd]);
%% Matlab file:
% All Matlab data structures can be saved into a binary, compressed file
% with the extension ".mat". These files have a HDF5-format, and are
% very convenient as long as you stay within Matlab.
outFileMatlab = 'data.mat';
save(outFileMatlab, 'dataMat');
disp([outFileMatlab ' has been generated in ' pwd]);