Soichiru
Soichiru

Reputation: 57

How to call a static class method from another method of the same class?

I'm trying to work with Octave and I couldn't find how to run some scripts that uses functions of a file, the last thing I tried was creating a class, but without success. The problem is some functions have inside anothers functions. For example:

classdef ALLFUNCS
   methods(Static)
      function result = SumElements(a,b,c)
          result = a + b + c;
      end
      function [prod,div] = MultiplyDivide(v1,v2,v3)
          prod = v1 * v2 * v3;
          div  = v1 / v2 / v3;
      end
      function resulta = powelents(a,b,c)
        pas = SumElements(a,b,c);
        resulta = pas*pas;
      end 
   end
end

In the command line I put

s2 = ALLFUNCS.powelents(3,4,5);

The error is:

error: 'SumElements' undefined near line 11 column 19
error: called from
powelents at line 11 column 17

So how can I solve this issue?

Upvotes: 2

Views: 408

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

Functions declared within a Methods Block are bound to their defining class (if static) or instances of the defining class (if not static). They don't have the typical Local Function scoping rules as in other contexts.

Therefore, the following line within the implementation of powelents

pas = SumElements(a,b,c);

does not have knowledge of the SumElements method (lexically) defined above powelents, so Octave and MATLAB will look for a SumElements on the search path in the global namespace and not find one.

The solution is to invoke the method using the class itself

function resulta = powelents(a,b,c)
    pas = ALLFUNCS.SumElements(a,b,c);
    resulta = pas*pas;
end 

This tells the run-time where to find the function definition.

Upvotes: 5

Related Questions