how to fprintf an matrix containing strings and numbers

7 次查看(过去 30 天)
So I have to print out a table consisting of two columns of numbers (not integers) and one column containing strings. I try to do the following, and no matter what I do, it gives me either cannot concatenate errors or just outputs incorrectly:
P=[6.5443 871.2282]
c=[6.7469 795.1066]
c1=[6.5472 870.5470 ]
c2=[6.4626 910.2019]
table=[P,c,c1,c2]';
words=['polyfit ';'basis functions';'nlinfit ';'L1 '];
words2=cellstr(words);
stuff={table,words}
fprintf('%6.4f \t %8f \t %s \n',stuff{:})
Output:
  • 6.5443 6.746877 6.547151e+00
  • 6.4626 871.228166 7.951066e+02
  • 870.5470 910.201907 pbnLoal1lsi yin fsf i i tft u n c t i o
Unfortunately, It prints out "table" first for the first 8 times and does not do what I want. Please help
  1 个评论
pfb
pfb 2015-4-18
编辑:pfb 2015-4-18
You have to admit that it is not very easy to guess what you want. You have a cell with a (8x1) numerical array and a (4x15) char array.
Then you ask matlab to print two numbers and one string out of it.
I can guess what you want, although I'm not sure why you want to do that in one single command. Why don't you use 4 fprintf commands?

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2015-4-18
Your code needed a few tweaks and a loop, but now it works:
P=[6.5443 871.2282];
c=[6.7469 795.1066];
c1=[6.5472 870.5470];
c2=[6.4626 910.2019];
table=[P;c;c1;c2];
words={'polyfit';'basis functions';'nlinfit';'L1'};
stuff={table,words};
for k1 = 1:size(words,1);
fprintf('%.4f \t %.4f \t %s \n',stuff{1}(k1,:),char(stuff{2}(k1)))
end
produces:
6.5443 871.2282 polyfit
6.7469 795.1066 basis functions
6.5472 870.5470 nlinfit
6.4626 910.2019 L1
The loop is usually necessary if you have mixed variable types.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by