how to substitute a variable in function
10 次查看(过去 30 天)
显示 更早的评论
So, i am trying to build a function that takes as input, a variable name, and i want to invoke the variable name inside the function and change it, based on the input. But somehow, that variable isn't being change, only the input variable
c = 0;
a = TestingFunctions2(c,4);
function [a] = TestingFunctions2(parameter,d)
b = 1
c = 1
parameter = d;
a = parameter
end
0 个评论
采纳的回答
KL
2017-11-9
编辑:KL
2017-11-9
You need to learn about how matlab workspaces work.
when you pass a parameter into a function, matlab creates a function workspace, i.e., a copy of all what you send in. Then all your computations are performed and finally only the outputs are returned. All those temporary variables you created are lost. If you don't assign the output to any of the existing base workspace variables, then you cannot expect to see the change happened inside the function call afterwards.
If you want c to change because of the function, you should have
function [a, parameter] = TestingFunctions2(parameter,d)
b = 1
c = 1
parameter = d;
a = parameter
end
and call it on the command line/main script like,
[a, c] = TestingFunctions2(c,4);
2 个评论
mm gs
2021-1-23
编辑:mm gs
2021-1-23
Hey KL! Thank you for your answer. I have a similar problem. Hope you can help me out.
necessary_input=6;
new_value=6;
awkward_calculation=myfunc(necessary_input,'b',new_value)
function s=myfunc(z,varargin)
a=5; b=2; d=0.01;
c=1; e=1;
%{Now here I want to change value of b to new_value}
s=z+a^2+b^2-3*b-2*d-e;
end
I have seen some people using structs inside the function (here). But then I need to change the expression
s=z+a^2+b^2-3*b-2*d-e;
Ofcourse I need validation of optional input arguments. Is there any other ways.
Summary: If I to change the value of a constant inside the function optionally, is it possible? How?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!