MATLAB: I tried to call a function but it failed

functionmatlab function

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

Best Answer

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.