英文:
Calling variables from one function to another in a class to in MATLAB
问题
我有主脚本文件和一个类文件。在类文件中,我有两个函数(funk
和 funk1
),在这些函数中,我有一些变量,我从主脚本中调用这些变量。
然而,如果我在类的一个函数中有一个变量,如何在类的另一个函数中使用相同的变量(可以是输入或输出)?以下是一个示例。
classdef ga_clas
% 电池约束
properties
%Property1
end
methods (Static)
function[a,b,c,d]=funk(f,g,h,i,j,k,l)
% 所有输入的值都来自主脚本
for j=1:24
g(j)=f(j)+k(j)
end
% g 是类中的变量,可以在另一个函数中用作输出,我不确定我是否使用正确。
end
function [g, M, N]=funk1(t,y,u,i,f)
% 如果我需要使用前一个函数(funk1)中的变量,它可以是输入或输出,那么我可以在这里使用吗?
end
end
end
英文:
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
答案1
得分: 2
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
%其他代码
[a, b, c, d, g] = ga_class(f, g, h, i, j, k, l)
2: 将g设置为ga_class的属性:
properties
g = [] %我不知道g的类型,可以赋值为0或其它类型
end
methods (Static)
function [a, b, c, d] = funk(self, f, g, h, i, j, k, l)
%传入的self将是ga_class的实例
for j = 1:24
g(j) = f(j) + k(j);
end
self.g = g; %这将把它分配给这个方法的属性
end
然后,稍后你可以这样调用:
ga_class.g
你很可能想要选择第一种方式,但第二种方式也是可行的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论