Rakshit Kothari
Rakshit Kothari

Reputation: 416

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

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?

Upvotes: 2

Views: 2402

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

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.

Upvotes: 1

H.Muster
H.Muster

Reputation: 9317

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

Upvotes: 3

Related Questions