0

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.

4
  • 1
    Loop no good ?. Commented Mar 2, 2018 at 10:27
  • @SardarUsama Well, I could do that. However, isn't there a more elegant way to solve that problem? Commented Mar 2, 2018 at 10:31
  • Your input is 2x3, do you want your str to also be 2x3 (cell array I assume) or is a 6x1 list okay? Commented Mar 2, 2018 at 10:34
  • @matlabgui It must be 2x3 cell array or string array. Commented Mar 2, 2018 at 10:40

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I wasn't aware of the compose function. It's exactly what I was looking for. Thanks.
0

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!! :)

3 Comments

reshape at the end, no? reshape(strread (....., size(mat)) btw the use of strread is not recommended by Mathworks. Mathworks recommends textscan instead.
true yes you could add that too! :) Although in the comment OP said either 2x3 or array,
The OP said "cell array" or "string array" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.