add blank spaces in cell array

15 次查看(过去 30 天)
AM
AM 2018-11-6
评论: Jan 2018-11-6
I have the following array
ar=
0 1 0 0 0 0 0 0 0 0
0 0 0 3 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 3 0
4 0 0 0 0 0 0 0 0 0
And I would like to create a 5x1 cell array C like this one:
C =
5×1 cell array
{' 0 1 0 0 0 0 0 0 0 0'}
{' 0 0 0 3 0 0 0 0 0 0'}
{' 0 0 0 0 0 0 2 0 0 0'}
{' 0 0 0 0 0 0 0 0 3 0'}
{' 4 0 0 0 0 0 0 0 0 0'}
That is with 10 blank spaces at the beginning of each row. I tried this:
fmt=repmat(' % 11.1i',1,10);
fmt=[' ' fmt4(2:end) '\n'];
rew=num2str(ar,fmt4)
tes=num2cell(ar)
C = cellfun(@cell2mat,num2cell(tes,2),'un',0)
And I get this:
C =
5×1 cell array
{'0 1 0 0 0 0 0 0 0 0'}
{'0 0 0 3 0 0 0 0 0 0'}
{'0 0 0 0 0 0 2 0 0 0'}
{'0 0 0 0 0 0 0 0 3 0'}
{'4 0 0 0 0 0 0 0 0 0'}
Is there a way to add the blank spaces in cell array C?
  1 个评论
Jan
Jan 2018-11-6
What does "That is with 10 blank spaces at the beginning of each row" mean for values with more than 1 digit?

请先登录,再进行评论。

采纳的回答

Jan
Jan 2018-11-6
编辑:Jan 2018-11-6
ar = [0,1,0,0,0,0,0,0,0,0; ...
0,0,0,3,0,0,0,0,0,0; ...
0,0,0,0,0,0,2,0,0,0; ...
0,0,0,0,0,0,0,0,3,0; ...
4,0,0,0,0,0,0,0,0,0];
fmt = repmat('%11d', 1, size(ar,2));
% Either:
C = sprintfc(fmt, ar); % Unfortunately not documented
% Or:
D = compose(fmt, ar) % Working since R2016b

更多回答(1 个)

Stephen23
Stephen23 2018-11-6
编辑:Stephen23 2018-11-6
>> ar = [0,1,0,0,0,0,0,0,0,0;0,0,0,3,0,0,0,0,0,0;0,0,0,0,0,0,2,0,0,0;0,0,0,0,0,0,0,0,3,0;4,0,0,0,0,0,0,0,0,0]
ar =
0 1 0 0 0 0 0 0 0 0
0 0 0 3 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 3 0
4 0 0 0 0 0 0 0 0 0
>> C = num2cell(reshape(sprintf('%11d',ar.'),[],size(ar,1)).',2);
>> C{:}
ans = 0 1 0 0 0 0 0 0 0 0
ans = 0 0 0 3 0 0 0 0 0 0
ans = 0 0 0 0 0 0 2 0 0 0
ans = 0 0 0 0 0 0 0 0 3 0
ans = 4 0 0 0 0 0 0 0 0 0

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by