How do I call another function in the same file from the first function
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi.
That is my code.
% function file
function [p1,p2,Name1,Name2]= Playerpoint(point1,point2)
point1 = 10; % get the points
point2 = 15;
p1 = point1+10;
p2= point2 +10;
Name1 = name1;
Name2 = name2;
fprintf("The first user %s has %d points\n",Name1,p1);
fprintf("The second user has %d points\n",Name2,p2);
end
function [name1,name2] = Playername(n1,n2)
name1 = n1;
name2 = n2;
end
% driver file
n1 = input('Please enter the first user name: ','s'); % let players enter the names
n2 = input('Please enter the second user name: ','s');
[name1,name2] = Playername(n1,n2);
[p1,p2,Name1,Name2]= Playerpoint(point1,point2);
In my code, i try to create two players and let them get their inital points.
But there are bug Unrecognized function or variable 'name1'.
That is my expected result:
Please enter the first user name: abby
Please enter the second user name: bob
The first user abby has 20 points.
The second user bob has 25 points.
댓글 수: 0
답변 (1개)
Harshal Ritwik
2023년 6월 16일
편집: Harshal Ritwik
2023년 6월 16일
Hi,
As per my understanding you want to know how to remove the error being generated while running the program. To remove the error, you must define the functions before calling the function. The error is being generated as you are not passing “name1” and “name2” parameters to the “Playerpoint” function. Also, you don’t need to pass “point1 and point 2” as parameters in the “Playerpoint” function as they are being defined inside the function. The following code snippet may help.
%Code Section
n1 = input('Please enter the first user name: ','s'); % let players enter the names
n2 = input('Please enter the second user name: ','s');
[name1,name2] = Playername(n1,n2);
[p1,p2,Name1,Name2]= Playerpoint(name1,name2);
function [p1,p2,Name1,Name2]= Playerpoint(name1,name2)
point1 = 10; % get the points
point2 = 15;
p1 = point1+10;
p2= point2 +10;
Name1 = name1;
Name2 = name2;
fprintf("The first %s user has %d points.\n",Name1,p1);
fprintf("The second %s user has %d points.\n",Name2,p2);
end
function [name1,name2] = Playername(n1,n2)
name1 = n1;
name2 = n2;
end
Please refer to the following documentation for more information.
I hope it helps!
Thanks.
댓글 수: 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!