How to save 3D data in text file?

11 views (last 30 days)
Jamie Al
Jamie Al on 1 Jun 2022
Answered: KSSV on 1 Jun 2022
I am trying to print my 3D data in a text file so I can perform some postprocessing. The form of my 3D data is the following:
%size Nx x Ny x Nz double
val(:,:,1) =
1.0e-03 *
-0.1330 -0.0709 0.1597 0.1604 -0.0717 -0.1323 -0.0717 0.1604 0.1597 -0.0709
-0.1298 -0.0725 0.1376 0.1380 -0.0730 -0.1294 -0.0730 0.1380 0.1376 -0.0725
-0.1158 -0.0565 0.1374 0.1377 -0.0567 -0.1155 -0.0567 0.1377 0.1374 -0.0565
-0.0752 -0.0363 0.0748 0.0748 -0.0363 -0.0752 -0.0363 0.0748 0.0748 -0.0363
-0.0355 -0.0119 0.0498 0.0498 -0.0120 -0.0355 -0.0120 0.0498 0.0498 -0.0119
-0.0077 -0.0028 0.0033 0.0033 -0.0028 -0.0077 -0.0028 0.0033 0.0033 -0.0028
-0.0041 0.0029 0.0171 0.0171 0.0029 -0.0041 0.0029 0.0171 0.0171 0.0029
-0.0112 -0.0058 0.0076 0.0076 -0.0058 -0.0112 -0.0058 0.0076 0.0076 -0.0058
-0.0237 -0.0086 0.0398 0.0399 -0.0087 -0.0236 -0.0087 0.0399 0.0398 -0.0086
-0.0272 -0.0167 0.0272 0.0273 -0.0168 -0.0271 -0.0168 0.0273 0.0272 -0.0167
-0.0291 -0.0132 0.0472 0.0474 -0.0134 -0.0288 -0.0134 0.0474 0.0472 -0.0132
val(:,:,2) =
...
How can I write this to text file?

Accepted Answer

KSSV
KSSV on 1 Jun 2022
m = 4; n = 3 ; p = 4 ; % dimensions for matrix
A = rand(m,n,p); % make a dummy 3d matrix
F = [repmat(' %0.4f',1,n),'\n']; % make the required format
fid = fopen('test.txt','w') ; % open file to write
% loop to write each 2D matrix
for i = 1:p
fprintf(fid,F,A(:,:,i).') ; % write the p'th matrix
fprintf(fid,'\n') ; % give empty space after a matrix is written
end

More Answers (0)

Categories

Find more on Data Import and Export 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!