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]]';

 採用された回答

Star Strider
Star Strider 2016 年 12 月 1 日

1 投票

See if this does what you want:
U={[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]};
Ud = reshape(cell2mat(U'), [], 2);
Out = sprintf('[%.0f,%.0f],', Ud');
Out = sprintf('[%s]', Out(1:end-1))
Out =
[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]

2 件のコメント

Tom Lichen
Tom Lichen 2016 年 12 月 1 日
That's wonderful! It does exactly what i wanted. Thank you,
Star Strider
Star Strider 2016 年 12 月 1 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (2 件)

James Tursa
James Tursa 2016 年 12 月 1 日
編集済み: James Tursa 2016 年 12 月 1 日

0 投票

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]]
dpb
dpb 2016 年 12 月 1 日
編集済み: dpb 2016 年 12 月 1 日

0 投票

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... :(

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by