How to print a 3D matrix to a text file?

How can I save the following 3D matrix in a text file using MATLAB?
Nx = 4;
Ny = 4;
Nz = 4;
x = (0:Nx-1)/Nx*2*pi;
y = (0:Ny-1)/Ny*2*pi;
z = (0:Nz-1)/Nz*2*pi;
[X,Y,Z] = meshgrid(x,y,z);
%how to save X, Y, and Z in text files?

3 Comments

You can directly write a matrix into a text file using writematrix()
Nx = 4;
Ny = 4;
Nz = 4;
x = (0:Nx-1)/Nx*2*pi;
y = (0:Ny-1)/Ny*2*pi;
z = (0:Nz-1)/Nz*2*pi;
[X,Y,Z] = meshgrid(x,y,z);
%how to save X, Y, and Z in text files?
X
X =
X(:,:,1) = 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 X(:,:,2) = 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 X(:,:,3) = 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 X(:,:,4) = 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124 0 1.5708 3.1416 4.7124
%writing in a text file
writematrix(X,'X.txt')
%showing the output
type 'X.txt'
0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469 0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469 0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469 0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469,0,1.5707963267949,3.14159265358979,4.71238898038469
However, is this the way you want to store the matrix?
If not, please give an example of how you would want to store a matrix
Just noticed this prints a text file that is readable as 16X256 instead of 16x16x16 and I wonder if it has to do with the readmatrix function or the way it's written into a text file. Thanks again.

Sign in to comment.

 Accepted Answer

As per my understanding, you are trying to save a 3D Matrix in a text file using MATLAB.
You could use writematrix() function to writes a homogeneous array to a comma delimited text file.
You can also refer to this MATLAB Answers post for saving a 3D matrix using MATLAB’s ‘save()’ function:
For more information on ‘writematrix’ and ‘save’ functions, please refer to the below links to their respective documentations:

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!