Andi
Andi

Reputation: 4855

MATLAB: Format string array

I am wondering how to apply a specific format to the newly available string array?

mat = [0, 0.4, 0.2 ; 0, 0.6, 0.8]
str = string(mat)

I would like the resulting string array to show always two decimals, followed by the percent sign (such as sprintf('%.2f%%', str)).

How am I supposed to do that? If it's not possible with a string array, a cell array of char would be equally fine.

Upvotes: 0

Views: 522

Answers (2)

matlabgui
matlabgui

Reputation: 5672

In instances like this a loop is generally fine, but you could do:

strread ( sprintf ( '%.2f%%\n', mat ), '%s', 'delimiter', '\n' )

But a loop is much easier to read going forward

As suggested by @SardarUsama you can also make it the same size as the original variable

reshape ( strread( sprintf ( '%.2f%%\n', mat ), '%s', 'delimiter', '\n' ), size(mat) )

P.S indeed strread is not recommended in the docs - but personally I find it a very useful function!! :)

Upvotes: 0

Sardar Usama
Sardar Usama

Reputation: 19689

If you have ≥ R2016b, you can use compose.

str = compose('%0.2f%%', mat);

str =

  2×3 cell array

    '0.00%'    '0.40%'    '0.20%'
    '0.00%'    '0.60%'    '0.80%'

For the older versions, using a loop (or arrayfun) is the straight-forward and elegant approach in my opinion.

res = arrayfun(@(x) sprintf('%.2f%%',x), mat,'un',0);

Upvotes: 4

Related Questions