调用变量从一个函数到另一个在一个类到在MATLAB

nvbavucw  于 2023-08-06  发布在  Matlab
关注(0)|答案(1)|浏览(135)

我有主脚本文件和一个类文件。在类文件中,我有两个函数(funkfunk1),在函数中,我有几个变量,我从主脚本调用。
但是,如果我在类的一个函数中有一个变量,我如何在类的另一个函数中使用相同的变量(它可以作为输入或输出)?下面是一个例子。

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

字符串

nnsrf1az

nnsrf1az1#

有两种方法。
1:正如Cris Luengo提到的,你可以返回g。这看起来像这样:

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

字符串
然后,当你调用funk时,你会这样做:

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


2:将g设置为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


之后,您可以拨打:第一个月
你很可能想要第一种方式,但也有可能用第二种方式。

相关问题