bongbang
bongbang

Reputation: 1712

MATLAB: populate cell array and format number

What's the efficient way to populate a cell array with values from a vector (each formatted differently).

For example:

V = [12.3 .004 3 4.222];

Desired cell array:

array = {'A = 12.30' 'B = 0.004' 'C = 3' 'D = 4'};

Is there an easier way than calling sprintf for each and every cell?

array = {sprintf('A = %.2f',V(1)) sprintf('B = %.3f',V(2)) ... }

Upvotes: 1

Views: 56

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

It can be done as follows:

V = [12.3 .004 3 4.222];
names = {'A', 'B', 'C', 'D'};
array = strcat(names(:), ' = ', ...
    strtrim(mat2cell(num2str(V(:), '%.4f'), ones(1,numel(V))))).';

How this works:

  • num2str gives a char matrix, using a format specifier (you may want to change the one I used).
  • mat2cell converts that into a cell array, putting each row into a cell.
  • strtrim removes spaces.
  • strcat concatenates cell-wise.

Upvotes: 1

Andrew Janke
Andrew Janke

Reputation: 23848

There's no vectorized form of sprintf that supports different formats, so you're mostly stuck with a sprintf call per cell. But you could arrange the code to be easier to deal with in a loop.

V = [12.3 .004 3 4.222];
names = num2cell('A':'Z');
formats = { '%.2f' '%.3f' '%d' '%.0f' };

c = cell(size(V));
for i = numel(V)
    c{i} = sprintf(['%s = ' formats{i}], names{i}, V(i));
end

It would be tricky to get anything faster than the naive way without dropping down to Java or C, because it's still going to take a sprintf() call for each cell, and that's going to dominate the execution time.

If you have a large number of elements and a relatively small number of formats, you could use unique() to group them up in to one sprintf() call per format, using the vectorized version of sprintf and then splitting on a delimiter to get individual strings. That may or may not be faster, depending on your exact data set and implementation.

Or you could write a MEX file that pushes the loop down in to C, looping over a call to C's sprintf. That would be faster, once you get up to moderately large input sizes.

Upvotes: 1

Related Questions