Unrecognized function or variable in live script

조회 수: 5 (최근 30일)
Jaafar Rammal
Jaafar Rammal 2021년 5월 8일
댓글: David Fletcher 2021년 5월 8일
I am running the following simple live script in Matlab Online:
a = 1
b(2)
function out = b(o)
out = a + o;
end
and I get the following error:
I am not sure how to make the function b use the variable a in this scenario. One of my postulations was that this is only a Matlab Online issue, but I can't verify this. I also tried using global a but it did not work.

채택된 답변

David Fletcher
David Fletcher 2021년 5월 8일
Variables are local to functions. The only (well strictly speaking not the only) way to get them into a function is to pass them in as an argument, and the only way to get them out is to pass them out. In this case you are passing 'o' into the function as an argument, so it is available - a is not being passed into the function so the function can't access it. You would either have to define a inside the function, or pass it into the function as an argument in the same way as you are passing o into the function.
  댓글 수: 2
Jaafar Rammal
Jaafar Rammal 2021년 5월 8일
Thanks, this makes sense
David Fletcher
David Fletcher 2021년 5월 8일
Global would work by the way, but you have to also define the global inside the function. I personally would advise against using global variables though

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 5월 8일
driver
function driver
a = 1
b(2)
function out = b(o)
out = a + o;
end
end
Shared variables require nested functions.
  댓글 수: 1
Jaafar Rammal
Jaafar Rammal 2021년 5월 8일
WORKS AS WELL
Thanks for the answer, neat trick and it works! (unfortunately I can only mark one answer as valid)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by