Index exceeds matrix dimensions

3 views (last 30 days)
Darren
Darren on 1 Mar 2013
Hi, the script i am working on is:
a = {'not follow', 'we are not ready', 'dont call',...
'footpush not pressed', 'proximity selected', 'clear hoist',...
'stop loading', 'no sequence start'};
b = {'follow', 'we are ready', 'call', 'footpush pressed',...
'call DA selected', 'load hoist', 'load bag', 'sequence start'};
x = dec2bin(hex2dec('7F'));
for i = 0:7
if x(7 - i + 1) == '0'
disp(a{i+1})
else
disp(b{i+1});
end
end
My code works fine when the hex value entered is between '80' and 'FF' however when i enter hex values between '00' and '7F' i get an error saying:
Index exceeds matrix dimensions.
Error in script (line 8)
if x(7 - i + 1) == '0'
Any help is much appreciated.

Accepted Answer

Cedric
Cedric on 1 Mar 2013
Edited: Cedric on 1 Mar 2013
When your hex code is below 0x80, the length of the string that you get with DEC2BIN is smaller than 8 chars.
Try with that:
x = hex2dec('7F') ;
for k = 1 : 8
if bitand(x, 2^(8-k))
disp(b{k}) ;
else
disp(a{k}) ;
end
end
Cheers,
Cedric
  5 Comments
Cedric
Cedric on 1 Mar 2013
Edited: Cedric on 1 Mar 2013
You're most welcome! DEC2BIN actually returns a string that is a representation of the binary code that corresponds to its argument; it is just for display purpose (or string processing) as its elements are chars '0' and '1' (which is what appears in your test). Now what I test is the value of each bit (within the first 8 bits) of the binary code that represents the decimal number outputted by HEX2DEC. I do this by performing an AND binary operation with 2^p. The latter generates 2^0=1d=00000001b, 2^1=2d=00000010b, 2^2=4d=00000100d, .., 2^7=128d=10000000b, for p =0,..,7 (in your case, p=8-k). You can see that bits with a 0 value will mask any bit value of the other operand in the binary AND operation, so the output of BITAND will be different from 0 only when bit number p is 1. Try the mechanism "by hand" to see how it works, e.g with decimal 9 whose 8 bits binary representation (as unsigned int) is 00001001:
>> x = 9 ;
>> bitand(x, 2^0) % Least significant bit (LSB).
ans =
1
>> bitand(x, 2^1)
ans =
0
>> bitand(x, 2^2)
ans =
0
>> bitand(x, 2^3)
ans =
8
So testing whether the output of BITAND is 0 or not provides you with the information about each bit value.
>> bitand(x, 2.^(7:-1:0)) ~= 0
ans =
0 0 0 0 1 0 0 1
Hope it helps!
Darren
Darren on 1 Mar 2013
Thanks very much, appreciated!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!