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

采纳的回答

Mark Sherstan
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);
  1 个评论
David Jenkins
David Jenkins 2019-3-1
Thank you very much!
I don't need elegance just functional code which your way does fine.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

标签

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by