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

7 次查看(过去 30 天)
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

回答(1 个)

Walter Roberson
Walter Roberson 2019-10-20
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.

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by