Function can't see variable

Question 1
Write a function-file can be used to calculate
equivalent resistance of n parallel connected resistor
function Req = equiv_parallel(r)
%r is an input of length n
%req is an output
%usage req= equiv_parallel(r)
%resistances' values
% for example r=[1 2 3 4 5]
r = [1 2 3 4 5]; %resistances' values
n = length(r); %number of resistor
Req = 1/sum(1./r); %sum of all parallel resistor
end
when I'm trying to run this code write as equiv_parallel(r) , matlab gives me "Undefined function or variable 'r'."

 采纳的回答

You're probably just clicking the green run triangle without passing in anything for r. Try assigning r first and then calling the function. And DON'T clobber the passed-in r by reassigning it to that vector [1,2,3,4,5]!
%r is an input of length n
%req is an output
%usage req= equiv_parallel(r)
%resistances' values
% for example r=[1 2 3 4 5]
r = [1 2 3 4 5]; %resistances' values
% Now call the function
Req = equiv_parallel(r)
Req = 0.4380
function Req = equiv_parallel(r)
n = length(r); %number of resistor
Req = 1./sum(1./r); %sum of all parallel resistor
end

1 个评论

thank you for your answer
%question 1
%write a function-file can be used to calculate
%equivalent resistance of n parallel connected resistor
function Req = resistors(r1,r2,r3,r4)
%r is an input of length n
%req is an output
r = [r1, r2, r3, r4];
Req = 1/sum(1./r); %sum of all parallel resistor
end
I wrote as resistors(1, 2, 3, 4) and it accept

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by