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

조회 수: 23 (최근 30일)
S
S 2015년 2월 6일
댓글: Star Strider 2015년 2월 9일
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