MATLAB 代码错误解析:索引无效和数组赋值问题

本文分析了以下一段 MATLAB 代码中出现的两个常见错误:

原始代码:

state='s1';
N=20;
seq=zeros(N,2);
fori=1:N;
    switch state
        case 's1'
            out=randsrc(1,1,[1 2 3;1/2 1/4 1/4]);
            if out==3
                state='s3';
            else
                state='s2';
            end
        case 's2'
            out=randsrc(1,1,[2 3;1/2 1/2]);
            if out==3
                state='s3';
            else
                state='s2';
            end
        otherwise
            out=1;
            state='s1';
    end
    if out==1
        seq(1i,:)='a1';
    elseif out==2
        seq(1i,:)='a2';
    else
        seq(1i,:)='a3';
    end
x=char(seq)

错误信息:

位置 1 处的索引无效。数组索引必须为正整数或逻辑值。

出错 Untitled (line 26)
    seq(1i,:)='a1';

错误分析:

该代码存在两个问题:

  1. for 循环语法错误: fori=1:N; 应该改为 for i=1:N。 循环变量 i 缺少赋值操作,导致代码无法正常执行。

  2. 数组赋值错误: seq(1i,:)='a1'; 应该改为 seq(i,:)='a1';。 此处 1i 代表复数,而 MATLAB 数组索引必须为正整数或逻辑值,导致错误。

代码修正:

state='s1';
N=20;
seq=zeros(N,2);
for i=1:N
    switch state
        case 's1'
            out=randsrc(1,1,[1 2 3;1/2 1/4 1/4]);
            if out==3
                state='s3';
            else
                state='s2';
            end
        case 's2'
            out=randsrc(1,1,[2 3;1/2 1/2]);
            if out==3
                state='s3';
            else
                state='s2';
            end
        otherwise
            out=1;
            state='s1';
    end
    if out==1
        seq(i,:)='a1';
    elseif out==2
        seq(i,:)='a2';
    else
        seq(i,:)='a3';
    end
end
x=char(seq)

总结:

本文通过解析 MATLAB 代码中常见的索引无效和数组赋值错误,并提供代码修正方案,帮助读者理解并解决类似问题。在进行 MATLAB 编程时,要格外注意语法细节,并仔细检查代码中的索引和赋值操作,确保代码的正确性和可读性。

MATLAB 代码错误解析:索引无效和数组赋值问题

原文地址: http://www.cveoy.top/t/topic/lNBX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录