How do I use sprintf to create a matrix of string and number arrays?

조회 수: 26 (최근 30일)
Neha
Neha 2014년 7월 25일
댓글: Ben11 2014년 7월 28일
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.

답변 (2개)

Michael Haderlein
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
  댓글 수: 1
Neha
Neha 2014년 7월 25일
sorry, I mean for the question to be getting an output of
abea 1
b 2
c 3
And between each column there should be a tab.

댓글을 달려면 로그인하십시오.


Ben11
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
Michael Haderlein 2014년 7월 28일
편집: Michael Haderlein 2014년 7월 28일
You don't need to use a loop:
sprintf('%s\t%d\n',v{:})
Ben11
Ben11 2014년 7월 28일
oh yes you're right thanks!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by