This writes a 3D matrix to a VTK file. An old text-based format is used because it is easy to write to. This may result in very large file sizes.
The matrix is normalised, kind of. Not sure why I did that; it might not be needed. The code is very short so feel free to experiment!
m = reshape(magic(6), [3 3 4]);
thanks for your code.
I met a problem in useing it
v = round(100 .* v(:) ./ mx);
The data format of I used is decimal，so I modified the code.
v = 100 .* v(:) ./ 100;
But the result is not correct.
Could you give some help?
Thanks for your code, it is really helpful.
Actually, i just modified the file to be more general to scalar data, using signed, floating points. No need to normalize, no need to have positive values :
For that, one can simply change " SCALARS blah char "
to "SCALARS blah float".
Then instead of :
use, for instance with a precision of 3 digits :
which will add only one blank space between each value whether it is positive or negative. (fwrite would actually add 2 blanks if the value is positive, fprintf understands the \040 ascii code as it's supposed to).
So, finally, we'd have :
fwrite(fid, ['# vtk DataFile Version 2.0' nl 'Volume example' nl 'ASCII' nl ...
'DATASET STRUCTURED_POINTS' nl 'DIMENSIONS ' ...
num2str(N) ' ' num2str(M) ' ' num2str(O) nl 'ASPECT_RATIO 1 1 1' nl ...
'ORIGIN 0 0 0' nl 'POINT_DATA ' ...
num2str(N*M*O) nl 'SCALARS matlab_scalars float 1' nl 'LOOKUP_TABLE default' nl]);
for z = 1:O
% Get this layer.
v = matrix(:, :, z)';
% Scale it. This assumes there are no negative numbers. I'm not sure
% this is actually necessary.
v = v(:)';
% Write the values as text numbers.
Tested with Paraview 4.1. Worked like charm.
According to your code, one should be careful as for the X and Y dimension. VTK structured data have x coordinates increasing faster, then y, and z.
By doing v = matrix(:, :, z);, the Y coordinates (rows) increase faster. Thus the VTK reader will assimilate the rows as the X dimension. So unless we transpose the matrix before sending it to writeToVTK, the VTK reader (paraview) will show us a transposed version of our arrays, X/Y -> Y/X. Am i correct ?
Good for export to VTK of matrices only.
Awesome! Great for viewing 3-D level-set data...and then making quick stereo movies in paraview..thanks Tim.
Create scripts with code, output, and formatted text in a single executable document.