user8357
user8357

Reputation: 29

How to display a string in a certain format

I'm writing a program that outputs a specific row of a matrix to the command window. However, I need to display it in a specific format as shown in the following:

Row: [2 4 6 8 10]

It should display the following:

1 (2%)

2 (4%)

3 (6%)

4 (8%)

5 (10%)

rather than just the answers in the command prompt as usual. Does anyone know of a way to do this in MATLAB? Thank you very much. Again, I have the calculation correct, I just don't know what tool to use to format it in the above way.

Upvotes: 0

Views: 86

Answers (2)

Adriaan
Adriaan

Reputation: 18177

rowc = [2 4 6 8 10];
A = [1:numel(rowc);rowc];
str = sprintf('%d (%d%%) \n',A);
disp(str)
1 (2%) 
2 (4%) 
3 (6%) 
4 (8%) 
5 (10%) 

sprintf let's you create a string in whatever format you want, check the docs for specifics on number caption and special characters.

Apparently the behaviour of sprintf is inherited from C, thus it will access any variables you insert in it as a long single column-vector (i.e. A(:), this is called linear indexing). Meaning that whether you enter two row vectors or two column vectors this code will not work. So you should create your input as a correct matrix considering linear indices, hence the extra line to declare A.

Upvotes: 1

IKavanagh
IKavanagh

Reputation: 6187

You can use arrayfun to loop through each element in the array and then use sprintf to format it correctly. The formatting you need specifically is

sprintf('%d (%d%%)\n\n', x, y)

where x is the leading value and y is the value inside the brackets. Then using arrayfun we have

>> cell2mat(arrayfun(@(x, y) sprintf('%d (%d%%)\n\n', x, y), 1:numel(rowc), rowc, 'UniformOutput', false))
ans =

1 (2%)

2 (4%)

3 (6%)

4 (8%)

5 (10%)

where rowc = [2 4 6 8 10];.

Another, simpler method with a single input function if the leading values should be divided by 2

>> cell2mat(arrayfun(@(x) sprintf('%d (%d%%)\n\n', x / 2, x), rowc, 'UniformOutput', false))
ans =

1 (2%)

2 (4%)

3 (6%)

4 (8%)

5 (10%)

Note: When arrayfun is used with 'UniformOutput', false the output is a cell array which we can then convert into a matrix of strings using cell2mat.

Upvotes: 1

Related Questions