How to put cell array in sprintf?

 Respuesta aceptada

Jos (10584)
Jos (10584) el 29 de Mayo de 2015
Use comma-separated list expansion. And you need to specify the format only once (see help fprintf)
A = {1 2 3 4}
sprintf('%d ',A{:})

Más respuestas (3)

Dasharath Gulvady
Dasharath Gulvady el 29 de Mayo de 2015

1 voto

 a={1,2,3,4,5};
 sprintf('%d,%d,%d,%d,%d',a{:});
Doug
Doug el 29 de Mayo de 2015

0 votos

mycell = {1,2,3,4,5};
s = sprintf('%d%d%d%d%d', mycell{:})
Jan Siegmund
Jan Siegmund el 25 de Ag. de 2020
Editada: Jan Siegmund el 31 de Ag. de 2020
If using multiple different cells:
%% Edited
% var = {'a','b','c','d','e'};
% num = {1,2,3,4,5};
% s = strjoin(cellfun(@(v,n)sprintf('%s = %d',v,n),var,num,'UniformOutput',false),'; ');
Stephen's comment for a proper solution

2 comentarios

Simpler and more efficient:
>> tmp = [var;num];
>> fprintf('%s = %d\n',tmp{:})
a = 1
b = 2
c = 3
d = 4
e = 5
Jan Siegmund
Jan Siegmund el 31 de Ag. de 2020
Editada: Jan Siegmund el 31 de Ag. de 2020
Oh, when sprintf and fprintf reported:
>> s = sprintf('%s = %d\n',var,num)
Error using sprintf
Function is not defined for 'cell' inputs.
I thougth sprintf and fprintf were not defined for cell arrays.
Edited: (And I did not think about the cell unpacking {:}
Anyways, yours is definitely the better solution!

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Preguntada:

el 26 de Mayo de 2015

Editada:

el 31 de Ag. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by