Undefined function or variable . which is defined in another workspace.

1 回表示 (過去 30 日間)
Neel Patel
Neel Patel 2021 年 2 月 16 日
コメント済み: Neel Patel 2021 年 2 月 17 日
Hello,
I have an problem and I made one code to solve that but I got an error.
Actually I have an function which I want to run in loop so I made function file and then make anouther programme to call that function but "for" loop variable is making error.
My code is somewhat complecated so I write here replica of that for example by which you all can have idea.
My function file code is:
function y=mytest(x)
y(t)=x(t)+1;
y=y(t);
end
and my programme file code is :
b=1:10;
myfun=@mytest;
for t=1:1:max(b)
a(t)=myfun(b(t));
end
I am getting thi error:
Undefined function or variable 't'.
Error in mytest (line 2)
y(t)=x(t)+1;
Error in myrun (line 4)
a(t)=myfun(x(t));
Please help me or suggest me what to do.
Thank you.

採用された回答

Walter Roberson
Walter Roberson 2021 年 2 月 16 日
b=1:10;
for t=1:1:max(b)
myfun = @(x) mytest(x,t); %<--- parameterized
a(t)=myfun(b(t));
end
function y=mytest(x,t) %<--- now receives t as well
y(t)=x(t)+1;
y=y(t);
end
This will fail, of course. You are passing the scalar b(t) into mytest, but you are expecting to be able to index it at t.
  1 件のコメント
Neel Patel
Neel Patel 2021 年 2 月 17 日
Thank you.
your given syntax "myfun = @(x) mytest(x,t);" helped me to solve problem.

サインインしてコメントする。

その他の回答 (1 件)

Ruger28
Ruger28 2021 年 2 月 16 日
編集済み: Ruger28 2021 年 2 月 16 日
You pass in a value that the function sees as x, but you are trying to use t. You need to pass your b(t) value AND your t value if you need them, but it looks like you just want to add one to your value.
b=1:10;
myfun=@mytest;
for t=1:1:max(b)
a(t)=myfun(b(t));
end
function y=mytest(x)
y=x+1;
% y(t)=x(t)+1;
% y=y(t);
end
  2 件のコメント
Neel Patel
Neel Patel 2021 年 2 月 16 日
編集済み: Neel Patel 2021 年 2 月 16 日
Thank you for answering.
This is example of my code not actual one. my code is complecated so I simply write
y(t)=x(t)+1;
but actully that is not my real objective.
let me create one more exaple.
if my function is :
function y=mytest(x)
y(t)=x(t)+x(t-1)+1;
y=y(t);
end
what now?
I need value of 't'.
Motive of my question is I need that value of 't' in fuction file automatically call value from
for t=1:1:max(b)
Neel Patel
Neel Patel 2021 年 2 月 16 日
If you want then I can give you my whole file but that may be take time to understand my perpose.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by