Problem converting cell to string
Afficher commentaires plus anciens
I want to convert my cell
U={[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]}
to a string that would look like this:
StringFromU ='[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]';
I've tried using this:
A = cell2mat(U)
allOneStringUUU = sprintf('%.0f,' , A);
allOneStringUUU = allOneStringUUU(1:end-1)
that gives this output
allOneStringUUU =
1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6
but i still need all of the [ and ] to be added. Could you please help me?
P.S. That U cell can be different size, so something like this
U={[1,4],[1,5]}
Should still be converted to this string:
StringFromU ='[[1,4],[1,5]]';
Réponse acceptée
Plus de réponses (2)
James Tursa
le 1 Déc 2016
Modifié(e) : James Tursa
le 1 Déc 2016
If the individual cells can have more than two elements, e.g.,
U={[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4,5],[3,5],[3,6,9]};
vec2str = @(v) ['[' sprintf('%.0f,' , v(1:end-1)) sprintf('%.0f' , v(end)) '],'];
Ucells = cellfun(vec2str,U,'uni',false);
Ustrings = [Ucells{:}];
Ustring = ['[' Ustrings(1:end-1) ']']
Ustring =
[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4,5],[3,5],[3,6,9]]
Well, you've just got to work on writing the proper format string(s) to use when you need them...an example specifically for the first (entered at command line; reformatted here to illustrate more clearly)--
>> s='[';
>> for i=1:length(U)-1,
s=[s sprintf('[%d,%d],',U{i})];
end,
s=[s sprintf('[%d,%d]]',U{end})];
>> s
s =
[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]
>>
In general you'll want to build a format string dynamically using the count of the arrays (repmat is very useful in this as in
fmt=['[' repmat('[%d,',1,N) '%d'];
for example. "Salt to suit" to make as generic as needs be depending on the form of inputs you must handle.
ADDENDUM
Had a few more minutes...
>> fmt=['[' repmat(['[' repmat('%d,',1,size(U{1},2)-1) '%d],'],1,numel(U)-1) '[%d,%d]]'];
>> s=sprintf(fmt,U{:})
s =
[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]
>>
As shows, not difficult, just tedious. Fortran FORMAT is MUCH more conducive to such shenanigans; while I grok why TMW went to the C-style to use the builtin libraries when converted Matlab to C, it's a sorry, sorry convention... :(
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!