SWITCH表达式必须是标量或字符向量常量

时间:2017-10-09 10:15:47

标签: matlab matlab-guide

对任何错误表示歉意仍在学习编程,也在MATLAB中。编写下面的代码是为了满足以下事实:如果Playerlocation是([0,1,2,3]),则该案例应该显示文本(您在Sunny Field中),如果Playerlocation是,我将添加它不是=([0,1,2,3])它应该显示一个不同的文本(你不在Sunny Field)我会很感激,如果我得到纠正并提前感谢

function describeLocation()
        clear all 
        close all

        global playerLocation;

     playerLocation = ([0, 1, 2, 3]);

    switch (playerLocation)

        case 0
            Text ='You are in a Sunny Field';
        disp(Text);

        case 1
            Text1 ='You are in a Sunny Field1';
        disp(Text1);

        case 2
            Text2 ='You are in a Sunny Field2';
        disp(Text2);

        case 3 
            Text3 ='You are in a Sunny Field3';
        disp(Text3);


    end  

1 个答案:

答案 0 :(得分:1)

switch语句的输入必须是标量或字符数组(由错误消息明确指定)。在您的情况下,playerLocation是一个导致错误的数组。

不是将整个数组传递给switch,而是应该遍历数组并分别传递每个标量成员

for k = 1:numel(playerLocation)
    switch (playerLocation(k))
    case 0
        Text ='You are in a Sunny Field';
        disp(Text);
    case 1
        Text1 ='You are in a Sunny Field1';
        disp(Text1);
    case 2
        Text2 ='You are in a Sunny Field2';
        disp(Text2);
    case 3 
        Text3 ='You are in a Sunny Field3';
        disp(Text3);
    end
end  

要缩短此范围,您可以在case对帐单中包含多个值

switch(playerLocation(k))
case {0, 1, 2, 3}
    disp('You are in a sunny field');
otherwise
    disp('You are not in a sunny field');
end

如果您正在尝试检查playerLocation 是否完全 [0, 1, 2, 3],那么switch声明并不是您想要的。您只需要一个正常的if语句

if isequal(playerLocation, [0, 1, 2, 3])
    disp('You are in a sunny field')
else
    disp('You are not in a sunny field');
end