How to save a matrix from the workspace to my computer as a dat file?
16 views (last 30 days)
Show older comments
Hello everyone, I am quite new to Matlab world and having some issues running my code. With the code I attached below, I am capable of creating the matrix I want to, and see it in the workspace. However when I want to save that matrix as raw binary int16 dat file to my desktop, I am having constant errors. Can someone help me out with that?
% get maximal number of files in directory
nfiles= 64
fileinfo = dir ("amp-A-000.dat");
num_samples = fileinfo.bytes/2; % int16 = 2 bytes
DATA=int16(zeros(num_samples, nfiles)); %empty matrix for all data
file_prefix = "amp-A-";
file_ext = ".dat";
for file_num = 0 : 63
file_num_str = num2str(file_num);
if file_num < 10
file_num_str = strcat("00", file_num_str);
elseif file_num >= 10 && file_num < 100
file_num_str = strcat("0", file_num_str);
end
file_name = strcat(file_prefix, file_num_str, file_ext);
fid = fopen(file_name, "r"); %here the expression amp-A-000 has to be made automatically into amp-A-(000)k
DATA(:,file_num+1)= fread(fid, num_samples, "int16");
fclose(fid);
end
%save a new binary file with ending *.dat
DATA = DATA';
1 Comment
Jan
on 25 May 2022
Edited: Jan
on 25 May 2022
Avoid such complicated inserting of zeros:
file_prefix = "amp-A-";
file_ext = ".dat";
file_num_str = num2str(file_num);
if file_num < 10
file_num_str = strcat("00", file_num_str);
elseif file_num >= 10 && file_num < 100
file_num_str = strcat("0", file_num_str);
end
file_name = strcat(file_prefix, file_num_str, file_ext);
by
file_name = sprintf('amp-A-%03d.dat', file_num);
How do you try to save the file and which errors do you get?
Accepted Answer
Jan
on 25 May 2022
folder = 'D:\Your\Outputfolder';
file = fullfile(folder, 'yourFile.dat');
[fid, msg] = fopen(file, 'W');
assert(fid > 0, msg);
fwrite(fid, Data, 'int16');
fclose(fid);
More Answers (0)
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!