How can I get the sprintf function to work for a cell array and a matrix?

23 次查看(过去 30 天)
I am writing a code in which I need to use the sprintf function to display the output values. The output values include 2 cell arrays and 5 matrices. For whatever reason I keep getting this error:
Error using sprintf
Function is not defined for 'cell' inputs.
This is the code I am currently using:
output(2)= {sprintf('%s \t %s \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f', probe_label, gene_label, [dtAm], [dtAstd]', [dtBm], [dtBstd]', [dtAB], [dt_pval_sig])};
probe_label and gene_label are the cell arrays and the rest are matrices.

回答(1 个)

Star Strider
Star Strider 2015-2-6
You have to convert them with char to use sprintf and its friends:
probe_label = {'abc' 'def' 'ghi' 'jkl'};
gene_label = {'mno' 'pqr' 'stu' 'vwx'};
[dtAm, dtAstd, dtBm, dtBstd, dtAB, dt_pval_sig] = deal(rand(4,1), rand(1,4), rand(4,1), rand(1,4), rand(1,4), rand(1,4));
for k1 = 1:size(probe_label,2)
output{k1,:} = sprintf('%s \t %s \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f', char(probe_label(k1)), char(gene_label(k1)), dtAm(k1), dtAstd(k1), dtBm(k1), dtBstd(k1), dtAB(k1), dt_pval_sig(k1));
end
I created the data, but this code should work with your data without modification (I hope).
  7 个评论
S
S 2015-2-9
The for loop seems to b working for me now. However I keep getting this error now:
Cell contents reference from a non-cell array object.
I modified the for loop to be similar to what Jan Simon suggested.
for k1 = 1:size(probe_label,2)
output{k1,:} = sprintf('%s \t %s \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f', probe_label{k1}, gene_label{k1}, dtAm{k1}, dtAstd{k1}, dtBm{k1}, dtBstd{k1}, dtAB{k1}, dt_pval_sig{k1});
end
What does this error mean and how can I fix it?
Star Strider
Star Strider 2015-2-9
Your numeric data aren’t cells. Change the ‘output’ assignment to:
output{k1,:} = sprintf('%s \t %s \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f \t %.3f', probe_label{k1}, gene_label{k1}, dtAm(k1), dtAstd(k1), dtBm(k1), dtBstd(k1), dtAB(k1), dt_pval_sig(k1));
and it should work
I didn’t test this change specifically, but it is only a minor variation on my original code. Note that only ‘probe_label{k1}’ and ‘gene_label{k1}’ have the curly-braces ‘{}’ cell reference, while your numeric arrays have standard parentheses ‘()’ array references. The referencing conventions can be a bit difficult to understand until you work with them.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by