I tried to call a function but it failed

2 visualizaciones (últimos 30 días)
Barry Allen
Barry Allen el 28 de Feb. de 2020
Comentada: Barry Allen el 3 de Mzo. de 2020
When i tried to return a value from the function (rate) to main file it failed and it shows undefined variable R_tow.
%main file
clc
clear all
close all
T=1;
tow_min=0;
tow_max=T;
tow=0.5
while (tow_max-tow_min)>0.02
tow_bar=(tow_max+tow_min)/2;
if crn(tow_bar)==crn(tow_min)
tow_min=tow_bar;
else
tow_max=tow_bar;
end
end
tow0=tow_bar;
disp("tow0="+tow0);
rate(tow0);
("R_tow="+R_tow);
plot(R_tow,tow0);
function R_tow=rate(tow)
PH0=0.1
Pa=10;
Q=20;
y=0.1;
N=3;
yi=[1,3,5];
Pdbar=0.2;
Pi=[3,4,2];
alpha=sqrt((2*y)+1)*qfuncinv(Pdbar);
beta=0
for i =2:N
x=1+((Pi(i)*yi(i))/((1+sum(Pi(i)*yi(3:N)))));
beta=beta+log2(x);
end
fs=100000;
z=1+sum(Pi(2:N).*yi(2:N));
S=(Pa*yi(1))/z;
x1=(1-(qfunc(alpha+(sqrt(tow*fs)*y))))
y1=log2(1+(((tow*Pa/1-tow)-sum(Pi(2:N)))*yi(1))/z)
R_tow=PH0*(1-tow)*x1*y1+beta;
%disp(R_tow)
end
  2 comentarios
Navid Zolfaghari Moheb
Navid Zolfaghari Moheb el 28 de Feb. de 2020
So change the last four line of your code to:
disp("tow0="+tow0);
R_tow = rate(tow0);
("R_tow="+R_tow);
plot(R_tow,tow0);
you have a function that returns a value and you call that value "R_tow". But this is local only to that function. Now if you want to use it in another function you have to tell that function to get the output from my 'rate' function and call it "R_tow". Having it defined as "R_tow = rate(tow)" in function does not mean that whenever I run rate(tow), I will have an output called R_tow. It means that it has an output but you have ot name it. For example, in your first function, you could have "y=rate(tow)" or "zeta = rate(tow)" or in this case "R_tow=rate(tow)".
Barry Allen
Barry Allen el 3 de Mzo. de 2020
Thanks
It helped

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 28 de Feb. de 2020
It is fundamental to the idea of functions in all programming languages that the variable names inside the function are internal to the function, that assigning to a variable inside the function does not affect the calling environment unless special arrangements are made.
Your assigning to the R_tow variable that belongs to the function rate() does not affect any variable outside of rate().
In order to get what you want, at the place you have
rate(tow0);
You need instead
R_tow = rate(tow0);
This R_tow is not the same variable as the one inside of rate(). Assignment of results is positional not according to name.

Más respuestas (0)

Categorías

Más información sobre Logical 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