How can I solve this question

2 次查看(过去 30 天)
1) In MATLAB command window, declare the variable COUNTER to be global with the global statement:
global COUNTER; % Declare COUNTER to be global.
COUNTER = 0; % Specify initial value.
This global variable is used to store the sum of the work pieces that two trucks have collected.
2) Declaring a variable to be global means that it is stored in the global workspace and not in a local workspace. Any function wanting to use this global variable must also include the statement. This statement must be placed at the beginning of the script or the function code before any attempt to use the variable is made. global COUNTER; % This tells MATLAB to use the global % variable and not create a local variable Create two user-defined MATLAB functions called PBTask4p2a_f.m (this function is for Truck A to input its count) and PBTask4p2b_f.m (for Truck B to input its count), respectively, to add the count from each truck to the global variable COUNTER. If the variable COUNTER exceeds 1000 after being added, the two programs should reset the COUNTER to 0. Call the two functions with count for each truck and display the updated value of COUNTER in command window.
For example: >> PBTask4p2a_f(200)
COUNTER = 200
>> PBTask4p2b_f(600)
COUNTER = 800
>> PBTask4p2a_f(300)
COUNTER = 0
  2 个评论
KALYAN ACHARJYA
KALYAN ACHARJYA 2020-4-24
There are sufficient hints in the question, any specific issue?
A M Saif Ben Kabir Amit
I manages to code like this.But after Run it show somwthing like this
Function 'PBTask4p2b_f' has already been declared within this scope.
global counter; % Declare COUNTER to be global.
counter = 0; % Specify initial value.
global counter; % This tells MATLAB to use the global
% variable and not create a local variable
a=input('truck a counter: ');
b=input('truck b counter: ');
function counter=counter+a+b
if counter>1000
counter =0
end
end
end

请先登录,再进行评论。

回答(1 个)

Pravin Jagtap
Pravin Jagtap 2020-4-27
编辑:Pravin Jagtap 2020-4-27
Hello,
As mentioned in the above comments, there are enough hints in question. This exercise will benefit you in understanding 'global' variables, their scope, and how to use them to achieve the task at hand.
Please refer to the following links to understand the usage of the 'global' variable.
Hope this will help you.

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by