how to substitute a variable in function
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Francisco Paupério
am 9 Nov. 2017
Bearbeitet: mm gs
am 23 Jan. 2021
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 Kommentare
Akzeptierte Antwort
KL
am 9 Nov. 2017
Bearbeitet: KL
am 9 Nov. 2017
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 Kommentare
mm gs
am 23 Jan. 2021
Bearbeitet: mm gs
am 23 Jan. 2021
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?
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!