Filter löschen
Filter löschen

fprintf confusion, multiple arrays to print

5 Ansichten (letzte 30 Tage)
David Jenkins
David Jenkins am 1 Mär. 2019
Kommentiert: David Jenkins am 1 Mär. 2019
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

Akzeptierte Antwort

Mark Sherstan
Mark Sherstan am 1 Mär. 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 Kommentar
David Jenkins
David Jenkins am 1 Mär. 2019
Thank you very much!
I don't need elegance just functional code which your way does fine.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by