0

How can I create a 4x4 array with hexadecimal input in matlab?

I'm currently getting this error:

Error using reshape To RESHAPE the number of elements must not change.

key =

  16×2 char array

    '41'
    '42'
    '43'
    '44'
    '45'
    '46'
    '47'
    '48'
    '49'
    '4A'
    '4B'
    '4C'
    '4D'
    '4E'
    '4F'
    '50'

w = (reshape (key, [4, 4]))';

1 Answer 1

2

Hexadecimal numbers in MatLab are actually text string.

In your case, you do not have a (16 x 1) array, but a 16 x 2 string array.

You can have a 4 x 4 array of decimal data by converting the hexadecimal values using the hex2dec function:

new_key=reshape(hex2dec(key),4,4)

Which gives:

new_key =

   65   69   73   77
   66   70   74   78
   67   71   75   79
   68   72   76   80

You can have a 4 x 4 string array of hexadecinal data by firdt converting the input array into a cell array:

c_key=cellstr(key)
c_key_1=reshape(c_key,4,4)

Which gives:

c_key_1 =
{
  [1,1] = 41
  [2,1] = 42
  [3,1] = 43
  [4,1] = 44
  [1,2] = 45
  [2,2] = 46
  [3,2] = 47
  [4,2] = 48
  [1,3] = 49
  [2,3] = 4A
  [3,3] = 4B
  [4,3] = 4C
  [1,4] = 4D
  [2,4] = 4E
  [3,4] = 4F
  [4,4] = 50
}

NOTE: Tested only with Octave

Sign up to request clarification or add additional context in comments.

1 Comment

Just a small correction: OP's array is a (16 x 2) char array, not string array. I suspect the reshaping would have worked fine if it was a string array, as it would have been the correct size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.