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

14 views (last 30 days)
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.

Answers (1)

Star Strider
Star Strider on 6 Feb 2015
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 Comments
S
S on 9 Feb 2015
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 on 9 Feb 2015
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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!