crazy_bean
crazy_bean

Reputation: 13

Array contents display in pairs

I have an array for example: A=[01 255 03 122 85 107]; and I want to print the contents as

  A=
   FF 01 
   7A 03   
   6B 55

Basically a read out from a memory. Is there any function in MatLab lib? I need to do this with minimum use of loops.

Upvotes: 1

Views: 65

Answers (1)

Divakar
Divakar

Reputation: 221504

Use this -

str2num(num2str(fliplr(reshape(A,2,[])'),'%1d'))

Output -

ans =
    21
    43
    65
    87

If you only want to print it as characters, use it without str2num, like this -

num2str(fliplr(reshape(A,2,[])'),'%1d')

Output -

ans =
21
43
65
87

General case with zeros padding -

A=[1 2 3 4 5 6 7 8 9 3] %// Input array
N = 3; %// groupings, i.e. 2 for pairs and so on
A = [A zeros(1,N-mod(numel(A),N))]; %// pad with zeros
out = str2num(num2str(fliplr(reshape(A,N,[])'),'%1d'))

Output -

out =
   321
   654
   987
     3

Edit for hex numbers :

Ar = A(flipud(reshape(1:numel(A),2,[])))
out1 = reshape(cellstr(dec2hex(Ar))',2,[])'
out2 = [char(out1(:,1)) repmat(' ',[numel(A)/2 1]) char(out1(:,2))]

Output -

out1 = 
    'FF'    '01'
    '7A'    '03'
    '6B'    '55'
out2 =
FF 01
7A 03
6B 55

Upvotes: 2

Related Questions