Using a function that will receive a variable number of values and return using the R equation? - Homework
    4 次查看(过去 30 天)
  
       显示 更早的评论
    
There is an equation R = (1/R1 + 1/R2 ... 1/Rn)^-1 I need to write a function that will take in varaibles and (no matter how many varaibles the user inputs), plug them into the equation and give the answer as R.
For example, if the function name is Req, Req(10) will return 10.0. Req(10,10) should return 5.
This is what I have so far. I am not sure how to approach this problem.
function eresistance( x,varargin)
fprintf('There is/are %d input argument.\n', nargin);
for i=1:nargin-1
    if ~ischar(varargin{i})
        fprintf('Input argument #%d is: %s\n',i, varargin{i});
        res = 1/varagin;
        inres = (res)^-1;
        fprintf('RESISTANCE: %.f\n',inres);
    else
        disp('PLEASE INPUT NUMBERS ONLY. \n');
    end
end  
end
0 个评论
采纳的回答
  sixwwwwww
      
 2013-11-2
        Dear Nora, you can do something like this:
if nargin == 0
    error('No input arguments')
else
    sum = 0;
    for x = 1:nargin
        if ~ischar(varargin{x})
            sum = sum + 1 / varargin{x};
        end
    end
    fprintf('The result is: %f\n', 1 / sum)
end
I hope it helps. Good luck!
2 个评论
  Image Analyst
      
      
 2013-11-2
				Nora's comment moved here:
I am getting this error:
Index exceeds matrix dimensions.
Error in eresistance (line 14)
        if ischar(varargin{x})
???
  Image Analyst
      
      
 2013-11-2
				Show your code. That exact code was not in that sixwwwwwwww gave, nor is it in your original question. You can attach it with the paper clip.
更多回答(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!