How to save a matrix from the workspace to my computer as a dat file?

16 次查看(过去 30 天)
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 个评论
Jan
Jan 2022-5-25
编辑:Jan 2022-5-25
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?

请先登录,再进行评论。

采纳的回答

Jan
Jan 2022-5-25
folder = 'D:\Your\Outputfolder';
file = fullfile(folder, 'yourFile.dat');
[fid, msg] = fopen(file, 'W');
assert(fid > 0, msg);
fwrite(fid, Data, 'int16');
fclose(fid);
  1 个评论
Tamer Kaya
Tamer Kaya 2022-6-23
Thank you so much Jan, and sorry for my very late answer. After creating the matrix, I was directly trying to fwrite without providing enough input arguments probably. Now it works perfectly!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by