0

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
user8357
  • 29
  • 1
  • 2
  • 5

2 Answers2

1
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.

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • `sprintf` is correct but this doesn't produce the correct output for the OP's problem. – IKavanagh Oct 10 '15 at 21:15
  • Yours outputs incorrect leading integers. They should be 1, 2, 3, 4, 5 but you have 1, 3, 5, 4, 8. – IKavanagh Oct 10 '15 at 21:21
  • @IKavanagh I just spent 10 minutes debugging that thing. Which idiot decided that `sprintf` takes variables as linear indices instead of like the first element of each vector, then the second of each etc... – Adriaan Oct 10 '15 at 21:31
1

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.

IKavanagh
  • 6,089
  • 11
  • 42
  • 47