Error-Variable might be used before it is defined

7 views (last 30 days)
I have defined some classes and two of them Called "Global" &"GlobalFlag".
All the classes are in one folder and same path.
But I got this warning that the "Variable might be used befire it is defined" and also after running I get the error " Global is not found in the current folder or on the MATLAB path, but exists in:"
Everything looks correct.
Any idea?
In this screenshot Die is also an object of a class.

Accepted Answer

Steven Lord
Steven Lord on 20 Nov 2022
This would work if SpeedMaxOpt is a Constant property of the Global class or a Static method of that class that can be called with 0 input arguments. But if SpeedMaxOpt is a regular (non-Constant) property or a regular (non-Static) method it needs to be associated with an instance of the object.
As a simple example, if you had a Human class it wouldn't make sense to ask Human.hairColor. Individual Human objects may have varying hairColor property values -- 'red', 'black', even 'none'. But if Human had a property isMammal we wouldn't need to know to which Human you're referring -- all Human objects will return true for isMammal.
Or in terms of methods, at least as far as we know we don't need to know which Human you're asking about when you ask what the closestStar is to the Human. No known Human is closer to another star than they are to the Sun.
classdef Human
properties % NOT Constant
isMammal = true;
function starName = closestStar
starName = 'the Sun';
With that code above, the first two of these lines of code would work. The third wouldn't. I suspect you're in the third scenario.
y = Human.isMammal
s = Human.closestStar
z = Human.hairColor
Here's what I get when I run those three lines in my MATLAB session.
>> y = Human.isMammal
y =
>> s = Human.closestStar
s =
'the Sun'
>> z = Human.hairColor
The property 'hairColor' in class 'Human' must be
accessed from a class instance because it is not a
Constant property.
  1 Comment
Steven Lord
Steven Lord on 22 Nov 2022
If the Global class has no properties, what is SpeedMaxOpt? Is it a method of the Global class? If it is, does it require an instance of the class on which to operate (like if I had a getHairColor method on the Human class) or should it be Static (like closestStar)?
If the former, if it requires an instance, what you've written won't work. You would need to first create an instance of the Global class then call the method with that object as input, either as:
y = Global;
s = y.SpeedMaxOpt;
y = Global;
s = SpeedMaxOpt(y);

Sign in to comment.

More Answers (0)


Find more on Construct and Work with Object Arrays in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!