- If you intend to execute both cases, increase the `data_num` to at least 2.
- If `case 2` might not always execute, initialize `pd1_2` and `pd2_2` outside the loop to avoid the undefined variable error.
- Before accessing `pd1_2` and `pd2_2`, add a check to ensure they are defined.
运行循环或者整段代码的时候报错“未定义函数或变量”,但单独执行该段代码会将添加路径的数据赋值给变量,并且相同路径的上一个变量的赋值就正常
8 次查看(过去 30 天)
显示 更早的评论
data_num=1;
for num1=1:data_num
switch num1
case 1
s4='F:\data\sourc1.txt';
sou4=load(strcat(s4));
pd1_1=sou4(1:2:end,:);
pd2_1=sou4(2:2:end,:);
case 2
s5='F:\data\source1.txt';
sou5=load(strcat(s5));
pd1_2=sou5(1:2:end,:);
pd2_2=sou5(2:2:end,:);
otherwise
disp('input data error')
end
NOTE: 只截取了程序的出错部分,无法在网站运行,还请各位论坛大神帮忙解答debug
报错:未定义函数或变量‘pd1_2'
0 个评论
回答(2 个)
Sugandhi
2024-9-11
The error you're encountering, "Undefined function or variable 'pd1_2'", occurs because the `case 2` block is never executed. This is due to the fact that the loop only runs once (`data_num = 1`), and thus, the `switch` statement only evaluates `case 1`. As a result, `pd1_2` and `pd2_2` are never defined. Possible workarounds:
jinjin lee
2024-9-12
很明显你那个switch是根据你的num1的值执行的,num1=1是只有pd1_1和pd2_1有值, pd1_2和 pd2_2均没有赋值也没有这两个变量,那么你后面的代码如果引用pd1_2和 pd2_2,那必然报错啊。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!