将数组元素转换为单个数字 [英] Convert array elements to single number

查看:120
本文介绍了将数组元素转换为单个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组A=[1,0,1,1,1,0].我想将其转换为十进制数B = 101110.我已经尝试了所有转换功能,但是找不到合适的解决方案.

I have an array A=[1,0,1,1,1,0]. I want to convert it to a decimal number B = 101110. I have tried all the conversion functions, but couldn't find an appropriate solution.

推荐答案

这可以很简单地通过以下方式完成:

This can be done quite simply this way:

B = sum(A.*10.^(numel(A)-1:-1:0))
B =
      101110

它的作用是将A中的每个数字都乘以10^n,其中n对应于向量中该位置对应的值.通过取这个新向量的总和,您将得到答案. 等效于:

What it does is take each number in A and multiply it with 10^n where n corresponds to the value appropriated with that place in the vector. By taking the sum of this new vector you'll get your answer. It's the equivalent of:

1*10^5 + 0*10^4 + 1*10^3 + 1*10^2 + 1*10^1 + 0*10^0

正如路易斯所说,它也可以按照以下方式完成

As Luis commented, it can also be done as

B = 10.^(numel(A)-1:-1:0) * A(:);

这篇关于将数组元素转换为单个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆