function s = ami_decode(a)n = length(a);s = zeros(1,n);sg = 1;for i = 1:n if a(i) == 0 s(i) = 0; elseif a(i) == 1 if mod(sg,2) == 0 s(i) = 0; else s(i) = 1; sg = sg + 1; end elseif a(i) == -1 if mod(sg,2) == 0 s(i) = 0; else s(i) = -1; sg = sg + 1; end end s(i) = s(i-1);endend MATLAB运行显示下标索引必须为正整数类型或逻辑类型。 出错 s(i)=s(i-1); 如何修改代码
时间: 2024-01-06 20:05:54 浏览: 90
可以将循环的第一次迭代单独处理,避免在第一次迭代时访问s的负数索引。可以在循环之前将s的第一个元素初始化为0,或者在第一次迭代时将s(i-1)替换为0。以下是修改后的代码:
```
function s = ami_decode(a)
n = length(a);
s = zeros(1,n);
sg = 1;
for i = 1:n
if a(i) == 0
s(i) = 0;
elseif a(i) == 1
if mod(sg,2) == 0
s(i) = 0;
else
s(i) = 1;
sg = sg + 1;
end
elseif a(i) == -1
if mod(sg,2) == 0
s(i) = 0;
else
s(i) = -1;
sg = sg + 1;
end
end
if i > 1
s(i) = s(i-1);
end
end
end
```
相关问题
输入以下是AMI码的解码代码和波形绘制代码: 解码代码: function s = ami_decode(a) n = length(a); s = zeros(1,n); sg = 1; for i = 1:n if a(i) == 0 s(i) = 0; elseif a(i) == 1 if mod(sg,2) == 0 s(i) = 0; else s(i) = 1; sg = sg + 1; end elseif a(i) == -1 if mod(sg,2) == 0 s(i) = 0; else s(i) = -1; sg = sg + 1; end end end end 波形绘制代码: n = 20; y = zeros(1,n); x1 = [ones(1,n/2) zeros(1,n/2)]; x0 = zeros(1,n); x2 = [-ones(1,n/2) zeros(1,n/2)]; z = zeros(size(1,nsn)); for i = 1:sn switch a(i) case 1 y = x1; case -1 y = x2; case 0 y = x0; end z(1,[(i-1)n+1:in]) = y; end ii = (1:nsn)/n; plot(ii,z); grid on;时,MATLAB中只显示AMI编码的波形 AMI解码波形为空,应如何修改
根据提供的代码,AMI解码波形为空可能是因为解码代码中的s向量没有被正确赋值。可以尝试在解码代码中加入以下语句,以确保解码后的s向量被正确赋值:
```
s(i) = s(i-1);
```
修改后的解码代码如下:
```
function s = ami_decode(a)
n = length(a);
s = zeros(1,n);
sg = 1;
for i = 1:n
if a(i) == 0
s(i) = 0;
elseif a(i) == 1
if mod(sg,2) == 0
s(i) = 0;
else
s(i) = 1;
sg = sg + 1;
end
elseif a(i) == -1
if mod(sg,2) == 0
s(i) = 0;
else
s(i) = -1;
sg = sg + 1;
end
end
s(i) = s(i-1);
end
end
```
加入这个语句后,解码后的s向量就能正确赋值,AMI解码波形也能正确显示。
function a = ami_code(s) %s=[1101000000010010000001] sn=length(s); sg=1; a=s; for i=1:sn if a(i)==1 if mod(sg,2)==0 a(i)=-1; end sg=sg+1; end end n=20; y=zeros(1,n); x1=[ones(1,n/2) zeros(1,n/2)]; x0=zeros(1,n); x2=[-ones(1,n/2) zeros(1,n/2)]; z=zeros(size(1,n*sn)); for i=1:sn switch a(i) case 1 y=x1; case -1 y=x2; case 0 y=x0; end z(1,[(i-1)*n+1:i*n])=y; end ii=(1:n*sn)/n; plot(ii,z);grid on;ylabel('AMI编码'); 写出上述AMI码对应的解码代码及调用代码
解码代码如下:
function s = ami_decode(a)
sn = length(a);
s = zeros(1, sn);
sg = 1;
for i = 1:sn
if a(i) ~= 0
if mod(sg, 2) == 0
s(i) = 0;
else
s(i) = a(i);
end
sg = sg + 1;
end
end
调用代码如下:
s = [1 1 0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1];
a = ami_code(s);
s_decode = ami_decode(a);
阅读全文