2

I have the following cell array:

>> tmp0 = {'foo', '%s', 'one'; 'bar', '%d', 3}

tmp0 =

  2×3 cell array

    'foo'    '%s'    'one'
    'bar'    '%d'    [  3]

I can use it like this with sprintf:

>> sprintf('%s,%d', tmp0{:,3})

ans =

    'one,3'

I would like to be able to achieve the same thing with a function call, since if I have a function that generates a cell array, say genCell(), I don't think I can achieve something like genCell(){:} in MATLAB.

So I made this function:

function cellExp(cellIn)
  cellIn{:}
end

Although dubious it seems to work as expected so far, since calling cellExp(tmp0(:,3)) seems to be the same as calling tmp0{:,3}

>> cellExp(tmp0(:,3))

ans =

    'one'


ans =

     3


>> tmp0{:,3}

ans =

    'one'


ans =

     3

However, ultimately, I cannot use it as desired:

>> sprintf('%s,%d', cellExp(tmp(:,3)))
Error using cellExp
Too many output arguments.
bbarker
  • 11,636
  • 9
  • 38
  • 62
  • 5
    I don't think this is doable. You need to pass a [comma-separated list](https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html) of arguments to `sprintf`, but a function can't return that. Even if your function uses [variable output arguments](https://www.mathworks.com/help/matlab/ref/varargout.html), you still have to explicitly get them all (i.e. it doesn't just dump them all as a comma-separated list). I don't think there's a very good way around using a temporary variable here. [Related question](https://stackoverflow.com/q/3627107/52738) – gnovice Sep 19 '19 at 15:40

1 Answers1

1

The last error message you are getting is because the output of cellExp(tmp0(:,3)) is comma-separeted list.

I am not sure exactly what you are looking for here, but I think this is one possibility for a function that will return your string based on a myCell = tmp0.

function myStr = mySprintf(myCell)

formatSpec = strjoin(myCell(:,2), ',');
[A1, A2] = myCell{:, 3};
myStr = sprintf(formatSpec, A1, A2);

end