Accessing value of a variable inside a function
显示 更早的评论
I have a variable, " c " defined outside a function as shown (just an example):
c=5;
function sum = add(a, b)
sum = a+b+c
end
Calling the add function by giving inputs for a, b Matlab throws an error saying : Local function name must be different from the script name. I want the value of the variable "c" to be accessed within the function so that if I give input of (2,3) for (a,b) I should be getting an output of sum = 10. Everything works fine if the variable " c " is inside the function but doesnt work when its outside the function. I tried to globally define the variable "c" like:
global c
c=5;
function sum = add(a, b)
global c
sum = a+b+c
end
But still Mathlab throws an error. Can anybody help me with this?
1 个评论
Stephen23
2020-12-30
I suspect that you should be parameterizing the function:
Avoid global variables, they cause more problems than they solve.
采纳的回答
更多回答(1 个)
Walter Roberson
2020-12-30
编辑:Walter Roberson
2020-12-30
0 个投票
When you define a script, and you define a function inside the script, then the name of the function cannot be the same as the name of the script.
Also, when you define a variable in a script, functions defined in the script do not have access to the variable. Shared variables are possible only with nested functions.
I suggest that you read
9 个评论
Mahith Madhana Kumar
2020-12-30
编辑:Mahith Madhana Kumar
2020-12-30
Image Analyst
2020-12-30
Upload add.m, time.m, and frequency.m.
Mahith Madhana Kumar
2020-12-30
编辑:Mahith Madhana Kumar
2020-12-30
Walter Roberson
2020-12-30
You cannot normally access a variable defined inside another function, but see
Mahith Madhana Kumar
2020-12-30
Image Analyst
2020-12-30
Did you put
global ff;
inside BOTH frequency.m AND time.m?
Mahith Madhana Kumar
2020-12-30
Mahith Madhana Kumar
2020-12-31
类别
在 帮助中心 和 File Exchange 中查找有关 Third-Party Cluster Configuration 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






