How do I use sprintf to create a matrix of string and number arrays?
31 次查看(过去 30 天)
显示 更早的评论
Here is an example of the data I want to output using sprintf
a = {'abea','b','c'}
b=[1 2 3]
How do I get it so the output is out =
abea 1
b 2
c 3
the variables a and b may be any length.
0 个评论
回答(2 个)
Michael Haderlein
2014-7-25
In such cases, I use
>> v=[a;num2cell(b)]
v =
'abea' 'b' 'c'
[ 1] [2] [3]
>> sprintf('%s %d ',v{:})
ans =
abea 1 b 2 c 3
Ben11
2014-7-27
编辑:Ben11
2014-7-27
Following on Michael's answer, what if you try this:
clear
clc
a = {'abea','b','c'};
b = [1 2 3];
b_cell = num2cell(b);
OutCell = cell(size(a,2),1);
for k = 1:size(a,2)
OutCell{k} = sprintf('%s %s',a{k},num2str(b_cell{k}));
end
disp(OutCell)
which gives this:
'abea 1'
'b 2'
'c 3'
2 个评论
Michael Haderlein
2014-7-28
编辑:Michael Haderlein
2014-7-28
You don't need to use a loop:
sprintf('%s\t%d\n',v{:})
另请参阅
类别
在 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!