本文介绍了扭转在Matlab一个逻辑位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在更好的方法来扭转X的元素?

 >> X = DEC2BIN(10)
X = 1010

我这样做:

  X(I)= num2str(1-str2num(X(I)))


解决方案

如果你想翻转位数值 NUM 的没有首先将其转换成一个字符数组的 0 1 ,那么你可以使用类似的,的和):

  NUM = BITXOR(NUM,4); %#翻转在4的位置的位(即第3位)
%# 要么 ...
NUM =位集(NUM,3〜bitget(NUM,3)); %#翻转位3

然而,如果你的的想要的字符数组进行操作,你也可以做到这一点很奇怪的事情:

  X(I)='A' -  X(I)
%# 要么 ...
X(ⅰ)= 97 - X(ⅰ);

这工作,因为 'A' X(I)首先被转换为它们的等效统一code UTF-16的数值前的数学运算是执行。由于对数值'A' 97,那么 0 (数值48)或 1 (数值49)从'A'将导致其他的数值。在等式当它被放回到字符数组中然后转换回为字符的右手侧将所得数值 X

Does it exist a better way to reverse an element of X?

>> X = dec2bin(10)
X = 1010

I did this:

x(i) = num2str(1-str2num(x(i)))
解决方案

If you want to flip a bit of a numeric value num without converting it first to a character array of '0' and '1', then you can use functions like BITXOR, BITGET, and BITSET (as Andrey also mentions):

num = bitxor(num, 4);  %# Flip the bit in the 4's place (i.e. bit 3)
%# Or ...
num = bitset(num, 3, ~bitget(num, 3));  %# Flip bit 3

However, if you do want to operate on the character array, you could also do this very strange thing:

X(i) = 'a' - X(i);
%# Or ...
X(i) = 97 - X(i);

This works because the characters 'a' and X(i) are first converted to their equivalent Unicode UTF-16 numeric values before the mathematical operation is performed. Since the numeric value for 'a' is 97, then a '0' (numeric value 48) or '1' (numeric value 49) subtracted from 'a' will result in the numeric value for the other. The resulting numeric value on the right hand side of the equation is then converted back to a character when it is placed back in the character array X.

这篇关于扭转在Matlab一个逻辑位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 08:01