0

suppose I have a irregular cell x:

x={{11,23},11.2,{22,1,222.3}}

I want a function celltostr where celltostr(x) returns a string '{{11,23},11.2,{22,1,222.3}}' or something like '11 23\n11.2\n22 1 222.3\n'. I try char([x{:}]) and it throws error. What should I do?

Paolo
  • 21,270
  • 6
  • 38
  • 69
Harry
  • 299
  • 2
  • 5
  • 14
  • 1
    With the parenthesis also? then you will need to write a complex function, as the parenthesis and commas are not really in `x`, they are just a way of showing a human data types in a human readable way. Why do you want to do this? Maybe there is an alternative solution to whichever problem you may be having – Ander Biguri Sep 10 '19 at 10:45
  • 1
    Do you want a character vector or a string as a result? Title says string but desired output says char vector. – Paolo Sep 10 '19 at 10:46
  • Parenthesis is optional, not neccessary. A function returns '11,23;11.2;22,1,222.3;' would be fine. '11,23\n11.2\n22,1,222.3\n' is also acceptable. I just want a string contains all original cell infomation. @AnderBiguri – Harry Sep 10 '19 at 10:53
  • I'm unfamiliar to Matlab and sorry for ambiguous. I think both string and char vector would be OK. @UnbearableLightness – Harry Sep 10 '19 at 10:59
  • [This](https://stackoverflow.com/q/38553645/2586922) may help if you want an arbitrary level of nesting or customized separators – Luis Mendo Sep 10 '19 at 13:57

1 Answers1

2

You could write a small helper function and iterate over the cell array:

x={{11,23},11.2,{22,1,222.3}};
formattedCharVectors = cellfun(@checkCellContents,x,'un',0);
stringOutput = strjoin([formattedCharVectors{:}],'');

function charVector = checkCellContents(x)
    if iscell(x)
        charVector = compose(repmat('%.1f,',1,size(x,2)),[x{:}]);
        charVector{1}(end) = ';';
    else
        charVector = [num2str(x) ';'];
    end

end

stringOutput is a char vector with the desired contents as per your comment:

>> stringOutput

stringOutput =

'11.0,23.0;11.2;22.0,1.0,222.3;'
Paolo
  • 21,270
  • 6
  • 38
  • 69