convert matrix from hexadecimal to decimal
10 views (last 30 days)
Show older comments
I have a large square matrix in hexadecimal notation and i need to transform it to decimal. for instance consider this:
A = [af 2 3; a2 b 9; c d f];
I want the result in the form:
A = [175 2 3;162 11 9; 12 13 15];
Since I have a very large matrix so I am not able to write {'af'} instead of [af] e.t.c.
2 Comments
Jan
on 4 Jan 2019
Edited: Jan
on 4 Jan 2019
Please start with providing the inputs in valid Matlab syntax. "[af 2 3; a2 b 9; c d f]" is not working as input. Now it matters if you mean:
A = {'af', '2', '3'; 'a2', 'b', '9'; 'c', 'd', 'f'}
or
A = ['af 2 3'; 'a2 b 9'; 'c d f']
or maybe this is a string found in a text file?
What does "not able to write {'af'} instead of [af] e.t.c" exactly mean? Where do the inputs come from?
Accepted Answer
Stephan
on 4 Jan 2019
Edited: Stephan
on 4 Jan 2019
Hi,
you could use hex2dec - depending on your input format / input data type this will work or not. I think this is why Jan asked in his comment. Consider the following examples:
>> A = ["af", "2", "3"; "a2", "b", "9"; "c", "d", "f"]
A =
3×3 string array
"af" "2" "3"
"a2" "b" "9"
"c" "d" "f"
>> A = hex2dec(A)
A =
175 2 3
162 11 9
12 13 15
or:
>> A = {'af', '2', '3'; 'a2', 'b', '9'; 'c', 'd', 'f'}
A =
3×3 cell array
{'af'} {'2'} {'3'}
{'a2'} {'b'} {'9'}
{'c' } {'d'} {'f'}
>> A = hex2dec(A)
A =
175
162
12
2
11
13
3
9
15
but the following is not really helpul::
>> A = ['af', '2', '3', 'a2', 'b', '9', 'c', 'd', 'f']
A =
'af23a2b9cdf'
>> whos A
Name Size Bytes Class Attributes
A 1x11 22 char
>> A = hex2dec(A)
A =
1.2035e+13
or consider the following, which gives an error message:
>> A = ['af 2 3 a2 b 9 c d f']
A =
'af 2 3 a2 b 9 c d f'
>> whos A
Name Size Bytes Class Attributes
A 1x19 38 char
>> A = hex2dec(A)
Error using hex2dec>hex2decImpl (line 58)
Input to hex2dec should have just 0-9, a-f, or A-F.
Error in hex2dec (line 21)
d = hex2decImpl(h);
>> A = ['af 2 3 a2 b 9 c d f']
A =
'af 2 3 a2 b 9 c d f'
>> A= split(A," ")
A =
9×1 cell array
{'af'}
{'2' }
{'3' }
{'a2'}
{'b' }
{'9' }
{'c' }
{'d' }
{'f' }
>> A = hex2dec(A)
A =
175
2
3
162
11
9
12
13
15
This 9x1 result can be reshaped easily:
A = reshape(A,3,3)
So you have to think about how you import the data to matlab and then you can easily convert the hexadecimal format to decimal notation. But, as shown, it strongly depends on how your data is formatted.
Best regards
Stephan
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!