fprintf confusion, multiple arrays to print
6 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Mark Sherstan
2019-3-1
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!