dimension mismatch with growing char matrix
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I have in a loop Name_Pairs growing
Name_Pairs(1,:) = sprintf('%s%d','p',10)
then
Name_Pairs(2,:) = sprintf('%s%d','p',1)
Subscripted assignment dimension mismatch.
Name_Pairs is first a 1x3 char, then I try to put in a 1x2 char.
Any ideas on how could this be arranged? thank you
0 个评论
采纳的回答
Walter Roberson
2017-3-6
Example:
Name_Paris(1:10, 1:3) = ' '; %initialize matrix to blanks
for k = 1 : 10
s = sprintf('%s%d','p',k);
Name_Pairs(1,1:length(s)) = s;
end
This would end up with ['p1 '; 'p2 '; 'p3 '; 'p4 '; 'p5 '; 'p6 '; 'p7 '; 'p8 '; 'p9 '; 'p10']
If you have R2016b or later you could instead do
Name_Pairs = strings(10, 1);
for k = 1 : 10
Name_Pairs(k) = sprintf('%s%d','p',k);
end
Or more compactly,
Name_Pairs = string('p') + (1:10).' ;
更多回答(1 个)
dpb
2017-3-6
>> num2str([10 1].','P%03d')
ans =
P010
P001
>>
numstr is vectorized.
To do with individual conversion again use a fixed-width field...
sprintf('P%03d',n)
on the RHS of the assignment. Or, use char to automagically pad the array...
>> Name= sprintf('%s%d','p',10)
Name =
p10
>> Name=char(Name, sprintf('%s%d','p',1))
Name =
p10
p1
>>
This has the effect of the names being truncated with no leading 0 in the field which has the side effect that wouldn't sort numerically as will the previous solution if that were to be wanted later for any reason, but each string is padded with blanks to the length of the longest which may also be or not be an issue in use.
The other way is to use cellstr which won't pad and has the other nicety that each string is an entity instead of an array so addressing is simpler...
>> clear Name
>> Name= {sprintf('%s%d','p',10)}
Name =
'p10'
>> Name=[Name; {sprintf('%s%d','p',1)}]
Name =
'p10'
'p1'
>>
In the latter note the {} to convert to cell string and the '' around each in the display; that's the visual klew that what you have is a cellstr array, not a char array.
0 个评论
另请参阅
类别
在 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!