MATLAB 将值向量转换为 uint32
我有一个包含值 0、1、2 和 3 的向量。我想要做的是从该向量中提取的每组 16 个元素中取出低两位,并将它们全部附加在一起以获得一个 uint32。 有人知道一个简单的方法来做到这一点吗?
追问:如果向量中的元素数量不是16的整数倍怎么办?
I have a vector containing the values 0, 1, 2 and 3. What I want to do is take the lower two bits from each set of 16 elements drawn from this vector and append them all together to get one uint32. Anyone know an easy way to do this?
Follow-up: What if the number of elements in the vector isn't an integer multiple of 16?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个矢量化版本:
Here's a vectorized version:
完善 Jacob 在他的答案中的建议和 mtrw 在他的评论中,这是我能想到的最简洁的版本(给定一个包含值 0 到 3 的 1×N 变量
vec
):这将数组中的第一个元素视为结果中的最低有效位。 要将第一个元素视为最高有效位,请使用以下内容:
编辑:这解决了问题的新修订...
如果向量中的元素数量不是16,那么您从中提取的最后一系列数字将少于 16 个值。 您可能需要用零填充该序列的较高位,使其成为 16 元素向量。 根据系列中的第一个元素是最低有效位 (LSB) 还是最高有效位 (MSB),您最终将以不同方式填充系列:
如果您想一次处理整个向量,请使用以下方法 您将如何执行此操作(包括任何必要的零填充):
当
vec(1)
是 LSB 时,以及当vec(1)
是 MSB 时,To refine what was suggested by Jacob in his answer and mtrw in his comment, here's the most succinct version I can come up with (given a 1-by-N variable
vec
containing the values 0 through 3):This treats the first element in the array as the least-significant bit in the result. To treat the first element as the most-significant bit, use the following:
EDIT: This addresses the new revision of the question...
If the number of elements in your vector isn't a multiple of 16, then the last series of numbers you extract from it will have less than 16 values. You will likely want to pad the higher bits of the series with zeroes to make it a 16-element vector. Depending on whether the first element in the series is the least-significant bit (LSB) or most-significant bit (MSB), you will end up padding the series differently:
If you want to process the entire vector all at once, here is how you would do it (with any necessary zero-padding included) for the case when
vec(1)
is the LSB:and when
vec(1)
is the MSB:我认为你应该看看 bitget 和
请注意,这将为您提供最高位中第一个向量的最后一位,所以您可能想要将 i 从 16 降到 1
I think you should have a look at bitget and bitshift. It should be possible to be something like this (pseudo-matlab code as I haven't worked with Matlab for a long time):
Note that this will give you the last bits of the first vector in the highest bits, so you might want to descend i from 16 to 1 instead