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!