运行循环或者整段代码​的时候报错“未定义函​数或变量”,但单独执​行该段代码会将添加路​径的数据赋值给变量,​并且相同路径的上一个​变量的赋值就正常

9 Ansichten (letzte 30 Tage)
Jiamin Ji
Jiamin Ji am 11 Sep. 2024
Kommentiert: Jiamin Ji am 13 Sep. 2024
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'

Antworten (2)

Sugandhi
Sugandhi am 11 Sep. 2024
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:
  1. If you intend to execute both cases, increase the `data_num` to at least 2.
  2. If `case 2` might not always execute, initialize `pd1_2` and `pd2_2` outside the loop to avoid the undefined variable error.
  3. Before accessing `pd1_2` and `pd2_2`, add a check to ensure they are defined.
  1 Kommentar
Jiamin Ji
Jiamin Ji am 13 Sep. 2024
Thanks very much for your so kind and patient answer, I have already solved it.

Melden Sie sich an, um zu kommentieren.


jinjin lee
jinjin lee am 12 Sep. 2024
很明显你那个switch是根据你的num1的值执行的,num1=1是只有pd1_1和pd2_1有值, pd1_2和 pd2_2均没有赋值也没有这两个变量,那么你后面的代码如果引用pd1_2和 pd2_2,那必然报错啊。
  1 Kommentar
Jiamin Ji
Jiamin Ji am 13 Sep. 2024
是的,已解决。感谢坛友友善耐心指出粗心小问题

Melden Sie sich an, um zu kommentieren.

Produkte


Version

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by