How can I print each piece of data in the following colum while iterating through a for loop with fprintf

7 views (last 30 days)
Hi,
I have multiple data sets that are 3x24 doubles. I want to use fprintf to arrange these into a table by iterating each through row of data by i. When I try to print it the data into the following colum after completing one row it will just put it in the same column.Capture.PNG
Capture.PNG

Answers (1)

Walter Roberson
Walter Roberson on 20 Oct 2019
It is possible to build up tables one column at a time. In order to do so, you need to work with character arrays and sprintf, or character arrays and num2str, or character arrays and the undocumented but very useful sprintfc() . The idea is that you would format a column as a fixed-width character array, and then put horzcat() the character array on to the end of the character array you are building up. Eventually you have the entire array build up, and you could then
fprintf('%s\n', strjoin( cellstr(All_cols), '\n'))
For example,
All_cols = '';
thiscol = num2str(Patchno(i,:), '%7d');
All_cols = [All_cols thiscol];
nrow = size(All_cols, 1);
blank_column = repmat(' ', nrow, 1);
thiscol = num2str(X(i,:). '%8.2f');
All_cols = [All_cols, blank_column, thiscol];
and so on.
These days, though, it is a lot easier if you have R2016b or later and use compose. For example,
compose('%7d %8.2f %10s', (1:2).', rand(2,1)*100, string({'hello'; 'sam'}))
compose() knows how to handle columns nicely. fprintf() always works down rows, and although it is not difficult to work with fprintf for multiple columns of pure numeric data, as soon as you mix in character variables, you start needing ugly tricks to get fprintf() to work.

Categories

Find more on Tables in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!