How to put cell array in sprintf?
81 次查看(过去 30 天)
显示 更早的评论
Data is in cell array: {1,2,3,4,5} sprintf('%d,%d,%d,%d,%d ',???);
0 个评论
采纳的回答
Jos (10584)
2015-5-29
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{:})
0 个评论
更多回答(3 个)
Jan Siegmund
2020-8-25
编辑:Jan Siegmund
2020-8-31
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 个评论
Stephen23
2020-8-25
Simpler and more efficient:
>> tmp = [var;num];
>> fprintf('%s = %d\n',tmp{:})
a = 1
b = 2
c = 3
d = 4
e = 5
Jan Siegmund
2020-8-31
编辑:Jan Siegmund
2020-8-31
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!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!