Search code examples
functionmatlabclass

Calling variables from one function to another in a class to in MATLAB


I have the main script file and a class file. In the class file, I have two functions (funk and funk1) and in the functions, I have several variables which I call from the main script.

However, if I have a variable in one function of the class, how can I use the same variable in another function of the class (it could be both as input or output)? Below is an example.

classdef ga_clas
% The battery constraints
properties
 %Property1
end
methods (Static)
 function[a,b,c,d]=funk(f,g,h,i,j,k,l) 
  % The value of all input are from main script 
  for j=1:24
   g(j)=f(j)+k(j)
  end 
  % g is the variable in the class that can be used as output in another function, I'm not sure whether I'm using it correctly or not.
 end
 function [g, M, N]=funk1(t,y,u,i,f)
  % and If I have to use variables from the previous function (funk1) which could be input or output then can I use it here?
 end 
end
end

Solution

  • There's two ways of doing this.

    1: as Cris Luengo mentioned, you can return g. This would look something like this:

    function[a,b,c,d,g]=funk(f,g,h,i,j,k,l) 
      for j=1:24
       g(j)=f(j)+k(j)
      end 
    end
    

    Then, when you call funk you would do:

    main
    %other code
    [a, b, c, d, g] = ga_class(f, g, h, i, j, k, l)
    

    2: set g as a property of ga_class:

    properties
      g = [] %i don't know what type g is could be assigned as 0 or whatever it's type is
    end
    methods (Static)
     function[a,b,c,d]=funk(self, f,g,h,i,j,k,l) 
    %self being passed in would be an instance of ga_class
      for j=1:24
       g(j)=f(j)+k(j)
      end 
      self.g = g %this assigns it into this method's properties
     end
    

    Then, later you can call: ga_class.g

    You most likely want the first way, but it is possible to do it the second way.