How should I write a matrix onto a text in Hex format?

2

I have a matrix, say:

M = [1000 1350;2000 2040;3000 1400];

I wish to write this matrix onto a text file in the hex format, like this:

0x000003e8 0x00000bb8  
0x000007d0 0x000007f8   
0x00000bb8 0x00000578  

I considered using the function dec2hex but it's very slow and inefficient. It also gives me the output as a string, which I don't know how to restructure for my above required format.

MATlab directly converts hex numbers to decimal when reading from a text file, ex. when using the function fscanf(fid,'%x').

Can we do the exact same thing while writing a matrix?

matlab
file-handling
printf
asked on Stack Overflow Oct 7, 2013 by Rakshit Kothari • edited Oct 7, 2013 by marsei

2 Answers

3

You can use the %x format string. For the sake of demonstration, see an example with sprintf below. If you want to write to a file, you will have to use fprintf.

M = [1000 1350;2000 2040;3000 1400];
str = sprintf('0x%08x\t0x%08x\n', M')

this results in

str =

0x000003e8  0x00000546
0x000007d0  0x000007f8
0x00000bb8  0x00000578
answered on Stack Overflow Oct 7, 2013 by H.Muster
1

You may use num2str with a format string:

str = num2str(M, '0x%08x ');

which returns

str =

0x000003e8 0x00000546
0x000007d0 0x000007f8
0x00000bb8 0x00000578

Using this instead of sprintf you do not need to repeat the format string for each column.

answered on Stack Overflow Oct 7, 2013 by Mohsen Nosratinia

User contributions licensed under CC BY-SA 3.0