matlab 用randi函数代替代码msg=randint(1,nsymbol,4); 的randint函数
时间: 2024-02-20 19:57:00 浏览: 158
好的,以下是使用randi函数替代randint函数的代码:
```
msg = randi([0, 15], [1, nsymbol]);
```
randi函数的第一个参数是一个包含两个元素的向量,用于指定随机数生成的范围。在本例中,我们将其设置为[0, 15],因为我们需要4位2进制数(即0000到1111)。第二个参数是一个包含nsymbol个元素的向量,用于指定生成的随机数的数量。
需要注意的是,randi函数生成的是整数而非浮点数,因此我们需要进行额外的转换来将其转换为二进制数。可以使用dec2bin函数将整数转换为二进制字符串,然后使用sscanf函数将其转换回数字格式。以下是完整的代码示例:
```matlab
nsymbol = 10;
msg = randi([0, 15], [1, nsymbol]);
binary_msg = dec2bin(msg, 4);
msg = sscanf(binary_msg', '%1d', [4, nsymbol])';
```
这个代码可以生成一个包含10个4位二进制数的随机向量。
相关问题
matlab中msg=randint(1,nsymbol,4);语句改为randi函数应为什么
在matlab中,`randint`函数已经被弃用,取而代之的是`randi`函数。如果要将`randint(1,nsymbol,4)`改为`randi`函数,应该这样写:
```matlab
msg = randi([0 3], 1, nsymbol);
```
其中,`[0 3]`表示产生0~3之间的随机整数,`1`表示生成一个随机整数向量,`nsymbol`表示向量的长度。
clear all nsamp=10; s0=ones(1,nsamp); s1=[ones(1,nsamp/2) -ones(1,nsamp/2)]; nsymbol=100000; EbN0=0:12; msg=randi(nsymbol,1); s00=zeros(nsymbol,1); s11=zeros(nsymbol,1); indx=find(msg==0); %比特0在发送消息中的位置 s00(indx)=1; s00=s00*s0; %比特0影射为发送波形s0 indx1=find(msg==1); %比特1在发送消息中的位置 s11(indx1)=1; s11=s11*s1; %比特1映射为发送波形s1 s=s00+s11; %总的发送波形 s=s.'; %数据转置,方便接收端处理 for indx=1:length(EbN0) decmsg=zeros(1,nsymbol); r=awgn(s,EbN0(indx)-7); %通过AWGN信道 r00=s0*r; %与s0相关 r11=s1*r; %与s1相关 indx1=find(r11>=r00); decmsg(indx1)=1; %判决 [err,ber(indx)]=biterr(decmsg,msg); end semilogy(EbNO,ber,-koEbNOgfunc(sqrt(10.^(EbN0/10)))); title('二进制正交信号误比特率性能') xlabel('EbN0');ylabel('误比特率Pe') legend('仿真结果理论结果')
这段代码是一个简单的二进制正交信号传输系统模拟程序。它实现了以下步骤:
1. 生成长度为 `nsymbol` 的随机二进制消息。
2. 将二进制消息映射为正交信号 `s`,其中比特0映射为 `s0`,比特1映射为 `s1`。
3. 将信号 `s` 通过 AWGN 信道,添加高斯白噪声。
4. 在接收端,将接收到的信号与 `s0`、`s1` 进行相关,并判决出接收到的二进制消息。
5. 计算误比特率 `ber` 并绘制误比特率性能曲线。
但是,这段代码中有一些错误:
1. 变量 `EbN0` 和 `EbNO` 拼写不一致,应该保持一致。
2. 在绘制误比特率性能曲线时,应该使用 `EbN0` 而不是 `EbNO`。
3. `biterr` 函数的输入参数顺序应该是实际比特序列在前,接收到的比特序列在后。
下面是修改后的代码:
```
clear all
nsamp = 10;
s0 = ones(1, nsamp);
s1 = [ones(1, nsamp/2) -ones(1, nsamp/2)];
nsymbol = 100000;
EbN0 = 0:12;
msg = randi(nsymbol, 1);
s00 = zeros(nsymbol, 1);
s11 = zeros(nsymbol, 1);
indx = find(msg == 0);
s00(indx) = 1;
s00 = s00 * s0;
indx1 = find(msg == 1);
s11(indx1) = 1;
s11 = s11 * s1;
s = s00 + s11;
s = s.';
for indx = 1:length(EbN0)
decmsg = zeros(1, nsymbol);
r = awgn(s, EbN0(indx) - 7);
r00 = s0 * r;
r11 = s1 * r;
indx1 = find(r11 >= r00);
decmsg(indx1) = 1;
[err, ber(indx)] = biterr(msg, decmsg); % 修改 biterr 的输入参数顺序
end
semilogy(EbN0, ber, '-ko', EbN0, qfunc(sqrt(10.^(EbN0/10)))); % 修改误比特率性能曲线绘制
title('二进制正交信号误比特率性能')
xlabel('EbN0'); ylabel('误比特率Pe')
legend('仿真结果', '理论结果')
```
阅读全文
相关推荐















