3

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.

MatlabDoug
  • 5,704
  • 1
  • 24
  • 36
Peterstone
  • 7,119
  • 14
  • 41
  • 49
  • 1
    see this related question about how SPRINTF/FPRINTF/NUM2STR deal with such input: http://stackoverflow.com/questions/2366680/how-can-i-create-a-cell-of-strings-out-of-a-meshgrid-in-matlab – Amro Nov 16 '10 at 20:27

2 Answers2

3

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.

gnovice
  • 125,304
  • 15
  • 256
  • 359
0

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").

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Y.T.
  • 31
  • 1
  • 2
    Welcome to SO, Y.T.. I've noticed you keep posting using new accounts. It's probably better to use just 1 account that has all your answers in one place. A moderator can help you with that if you like. Also, adding "Y.T." or a link to your blog to the end of your post isn't necessary or generally acceptable on SO. Your name is already on your post in the bottom right corner, and a link to your blog is already in your profile. I also suggest for all new users to give the [FAQ](http://stackoverflow.com/faq) a good read. ;) – gnovice Nov 23 '10 at 15:40