Problem converting cell to string
조회 수: 4 (최근 30일)
이전 댓글 표시
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]]';
댓글 수: 0
채택된 답변
Star Strider
2016년 12월 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개)
James Tursa
2016년 12월 1일
편집: James Tursa
2016년 12월 1일
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]]
댓글 수: 0
dpb
2016년 12월 1일
편집: dpb
2016년 12월 1일
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... :(
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!