How to use fprintf with two arrays?

6 views (last 30 days)
Hi! I'm trying to coalesce two arrays (X and Y) into a text file ('XYresults.txt'). The arrays are both 643x1 and I am trying to get X as the right column, and Y as the left. This is what I have written,
fileID = fopen('XYresults.txt','w');
fprintf(fileID,'%1s %2s\n','X data','Y data');
fprintf(fileID,'%1d %2d\n','X','Y');
fclose(fileID);
but when I run the code and open XYresults.txt, the only results are:
X data Y data
88 89
Does anyone have any advice as to why more data isn't being written? Thank you!

Accepted Answer

the cyclist
the cyclist on 27 Aug 2021
Edited: the cyclist on 27 Aug 2021
Assuming that X and Y are variables in your workspace, you need
fprintf(fileID,'%1d %2d\n',X,Y);
rather than
fprintf(fileID,'%1d %2d\n','X','Y');
Your code is writing the ASCII values of the characters 'X' and 'Y'.
  4 Comments
Image Analyst
Image Analyst on 27 Aug 2021
And obviously
fprintf(fileID,'%1s %2s\n','X data','Y data');
can/should be
fprintf(fileID,'X data, Y data\n');
Grace Pooley
Grace Pooley on 27 Aug 2021
That's not necessarily obvious for folks who aren't used to the syntax, thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!