fprintf confusion, multiple arrays to print

6 ビュー (過去 30 日間)
David Jenkins
David Jenkins 2019 年 3 月 1 日
コメント済み: David Jenkins 2019 年 3 月 1 日
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 Center および File ExchangeData Type Conversion についてさらに検索

タグ

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by