필터 지우기
필터 지우기

Help with calling functions / too many outputs?

조회 수: 2 (최근 30일)
Tony
Tony 2015년 8월 5일
댓글: Star Strider 2015년 8월 24일
Hi, here I have listed two functions, the first (part of PR) which calls the second (phi) on the last line. Every time I try, I get an error using phi about too many output arguments. Phi runs perfectly, but what should I change to I can continue to use phi in other programs with error?
function PR(k)
if k > 1
for i = 1:k
if rem(k,i)==0
y(i) = k./i;
else
y(i) = 1;
end
end
for j = 1:k
for m = 1:k
z(m) = y(m).^j;
if mod(z(m)-1,phi(k))==0
=============================================================
function phi(k)
%This function takes an integer input and calculates the Phi of that number
%(Euler's Phi function)
k = abs(k);
if k > 1 && rem(k,1)==0
for i = 1:k
if gcd(i,k) == 1
y(i) = 1;
else
y(i) = 0;
end
end
W = sum(y);
else
disp('Make sure k is an integer and greater than 1')
end
end

채택된 답변

Star Strider
Star Strider 2015년 8월 5일
It’s difficult to follow your code, so I can’t provide an exact solution. However in general, if you want to return a value from a function, you have to state that as part of the function declaration statement:
function out = squared(in)
out = in.^2;
end
then call it for example as:
y = squared(2);
to have it return the result to the workspace that called it.
  댓글 수: 2
Tony
Tony 2015년 8월 24일
Just a little clarification. When I use the code:
"function out" am I asking matlab to prepare to output something from that function?
Also, could you clarify exactly what matlab is doing when you put "out = in.^2?" I just want to know for future reference.
Star Strider
Star Strider 2015년 8월 24일
The function declaration is the first line in a function file. That line begins with the keyword function and then the calling syntax for the function. So you would call that function as:
arg = 2;
val = squared(arg);
with ‘val’ containing the result of the function call.
Here, ‘out’ is the variable returned by the function. Some statement within the code for ‘squared’ has to assign a value to that variable. The function call itself can have any argument names, so long as they are of the correct number and class that the function needs, and the output can have any variable name assigned to it, as in the example code here.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by