3
votes

I´m trying to printing comparative columns to compare elements with the same index of two or three differents vector. I will illustrate my question with the next example

>> a = [5.47758 7.46578 3.45323]
a =

5.4776    7.4658    3.4532

>> b = [5.65432 4.45678 2.34789]

b =

5.6543    4.4568    2.3479

Now if I write

>> sprintf('%.2f %.2f\n',a, b)

I get the following response from Matlab

ans =
5.48 7.47
3.45 5.65
4.46 2.35`

But what the way I would like to see this presentation of values is this

ans =
5.48 5.65  
7.47 4.46 
3.45 2.35

How can I use the function sprintf (or other function or way) to get the above representation? Thank you.

2
see this related question about how SPRINTF/FPRINTF/NUM2STR deal with such input: stackoverflow.com/questions/2366680/… - Amro

2 Answers

3
votes

You can fix this problem by concatenating a and b into one 2-by-3 matrix input argument:

>> sprintf('%.2f %.2f\n',[a; b])

ans =

5.48 5.65
7.47 4.46
3.45 2.35

The SPRINTF function works by reusing the formatting string over and over as it traverses (in column order) the elements of each of the input arguments in the order they are entered. That's why in your example all the values of a get printed, then all the values of b, instead of interleaving the values of a and b.

0
votes

If you are just "printing" it on the screen, you could type on the MATLAB Console (or "Command Window"):


a = [5.47758 7.46578 3.45323];
b = [5.65432 4.45678 2.34789];

c = [a',b']; % Transposing each row vector into a column vector before forming a matrix

c =

    5.4776    5.6543
    7.4658    4.4568
    3.4532    2.3479

This will make it easier when you sort the matrix by rows, for example, using the command 'sortrows' (See the doc on 'sortrows' for its usage: "help sortrows" or "doc sortrows").