dimension mismatch with growing char matrix
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nicolas
el 6 de Mzo. de 2017
Comentada: Nicolas
el 7 de Mzo. de 2017
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 comentarios
Respuesta aceptada
Walter Roberson
el 6 de Mzo. de 2017
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).' ;
Más respuestas (1)
dpb
el 6 de Mzo. de 2017
>> 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 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!