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'."

 Accepted Answer

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 Comment

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

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!