how to make a global counter with two functions

6 ビュー (過去 30 日間)
shelly
shelly 2018 年 10 月 1 日
コメント済み: Rik 2018 年 10 月 1 日
stuck on a problem here: 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
i made an attempt here but i know im using function and global incorrectly and im not sure what else to do
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
  4 件のコメント
jonas
jonas 2018 年 10 月 1 日

Read more about how to define functions

Rik
Rik 2018 年 10 月 1 日

You should save the two functions to separate files. That way you can call them independently of eachother.

And you should complain to your instructor. The use of globals is a bad idea, which should only be showcased as a warning. Sometimes you do indeed need them, but the should be used as little as possible. So far, I have only found a single situation in which I had to use a global.

When using globals, avoid using names you or other people might be using as well. The easiest way to do that is including the function name (and maybe a short descriptor) in the name of the variable.

function SomeFunctionThatNeedsGlobal
global SomeFunctionThatNeedsGlobal___counter___NumberOfPixelsAnalyzed
%now you can continue using counter as a variable while you are sure that
%no name-collision is happening
%store any edits back to the global
SomeFunctionThatNeedsGlobal___counter___NumberOfPixelsAnalyzed=counter;
end

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by