how to substitute a variable in function

10 visualizaciones (últimos 30 días)
Francisco Paupério
Francisco Paupério el 9 de Nov. de 2017
Editada: mm gs el 23 de En. de 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

Respuesta aceptada

KL
KL el 9 de Nov. de 2017
Editada: KL el 9 de Nov. de 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 comentarios
Francisco Paupério
Francisco Paupério el 9 de Nov. de 2017
Thank you very much for the help! :)
mm gs
mm gs el 23 de En. de 2021
Editada: mm gs el 23 de En. de 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?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by