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

采纳的回答

KL
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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by