fprintf confusion, multiple arrays to print

5 views (last 30 days)
I want to create a text file containing a variety of data and I am unsure how to use the fprintf function to actually achieve this.
The following commands produce exactly want I want in my text file.
disp(SomeIdentifier); %is just a variable equal to 1
disp(boxMatrix); % a 3x3 array containing numbers
disp(atomTypes); % a 1x3 array containing characters
disp(atomCounts); % a 1x3 array containing numbers
disp(atomCoords); % a 20x3 array containing numbers
vaspID = fopen('filename','w')
fprintf(vaspID,
I am stuck as far as what to put after vaspID to achieve the result I want.
Thank you for your help

Accepted Answer

Mark Sherstan
Mark Sherstan on 1 Mar 2019
Not the most effcient code but this should help your understanding. Also refer to this link for some of the different formating options for fprintf: https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html
SomeIdentifier = 1;
boxMatrix = [1 2 3; 4 5 6; 7 8 9];
atomTypes = ['N' 'O' 'F'];
atomCounts = [7, 8, 9];
atomCoords = rand([20,3]);
disp(SomeIdentifier); %is just a variable equal to 1
disp(boxMatrix); % a 3x3 array containing numbers
disp(atomTypes); % a 1x3 array containing characters
disp(atomCounts); % a 1x3 array containing numbers
disp(atomCoords); % a 20x3 array containing numbers
vaspID = fopen('test.txt','w');
%is just a variable equal to 1
fprintf(vaspID,'%d\n',SomeIdentifier)
% a 3x3 array containing numbers
for ii = 1:size(boxMatrix,1)
fprintf(vaspID,'%d\t',boxMatrix(ii,:));
fprintf(vaspID,'\n');
end
% a 1x3 array containing characters
for ii = 1:length(atomTypes)
fprintf(vaspID,'%c\t',atomTypes(1,ii));
end
fprintf(vaspID,'\n');
% a 1x3 array containing numbers
for ii = 1:length(atomCounts)
fprintf(vaspID,'%d\t',atomCounts(1,ii));
end
fprintf(vaspID,'\n');
% a 20x3 array containing numbers
for ii = 1:size(atomCoords,1)
fprintf(vaspID,'%0.3f\t',atomCoords(ii,:));
fprintf(vaspID,'\n');
end
fclose(vaspID);
  1 Comment
David Jenkins
David Jenkins on 1 Mar 2019
Thank you very much!
I don't need elegance just functional code which your way does fine.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!