How to convert a numerical matrix into a matrix of formatted strings?

Hi,
I'd like to convert a numerical matrix into a matrix of formatted strings.
Example of input matrix:[1 2 3.051 4]
What I expect as output: {'1.00' '2.00' '3.05' 4.00'} specified by the string format '%.2f' for instance.
Thanks for your tips.
[EDITED, JSimon, 06-Oct-2011 14:16 UTC]: Cell string wanted => square brackets to curly braces.

Réponses (4)

Thank you for your answer but what I expect is not one string as make sprintf but a matrix of strings.
Finally, I found a solution myself:
V=[1;2;3.051;4];
M=[V 2*V];
Format='%.2f';
Delimiter=';';
Format=[Format Delimiter];
C=cell(size(M));
for i=1:size(M,1)
RemainderString=sprintf(Format,M(i,:));
j=0;
while true
[Token RemainderString]=strtok(RemainderString,Delimiter);
if isempty(Token)
break;
end
j=j+1;
C{i,j}=Token;
end
end

2 commentaires

Shorter solution:
V=[1;2;3.051;4];
M=[V 2*V];
C = arrayfun(@(x)sprintf('%.2f',x),M,'Uniform',false)
Or as loop:
C = cell(size(M)); for i=1:numel(M); C{i}=sprintf('%.2f', M(i)); end
Using the linear index for M and C reduces the complexity.

Connectez-vous pour commenter.

Benjamin
Benjamin le 12 Oct 2011
Action closed.
Thanks a lot for all your answers!
Kind regards.

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by