[英]MatLab: Variable assigned during function can be used in another function
I have a function with an output q. 我有一个输出q的函数。 This function will generate a matrix, A, in order to find q.
此函数将生成矩阵A,以便找到q。 Matrix A is 100x100x100, so it takes a really long time to run this code and I want to do (lots) of other calculations with the information from A without having to run that code over and over again.
矩阵A是100x100x100,因此运行此代码需要很长时间,我想用A中的信息进行(大量)其他计算,而不必一遍又一遍地运行该代码。
Is there a way to make both q and A (q has dimensions 100x1) accessible in another function without running the original function each time? 有没有办法让q和A(q的尺寸为100x1)可以在另一个函数中访问而不必每次都运行原始函数?
I though about using "global" but I'm not sure how that works. 我虽然使用“全球”,但我不确定它是如何工作的。
You can use 您可以使用
assignin('base', 'var1', var1)
To assign variable var
in the base work-space. 在基础工作空间中分配变量
var
。 This will allow you to parse it to other functions and it will persist. 这将允许您将其解析为其他功能,它将持续存在。
Alternatively you can simply return it: 或者你可以简单地返回它:
function [other_vars var1] = theFunk(input)
Then to use it in other functions you can make it global: 然后在其他函数中使用它可以使它成为全局函数:
global VAR_GLOBAL = var;
and in your function use: 并在您的功能使用:
function [stuff] = someOtherFunction(input)
global VAR_GLOBAL
% Do some stuff with VAR_GLOBAL
or simply pass it into your other functions: 或者只是将其传递给您的其他功能:
function [stuff] = someOtherFunction(input, var1)
It appears to me that your function is doing two separate things, and needs some refactoring... 在我看来,你的功能是做两件事,需要一些重构......
Consider extracting the part that computes the matrix A
into a separate function. 考虑将计算矩阵
A
的部分提取到单独的函数中。 The other function will take the produced matrix A
as input and compute the output q
. 另一个函数将生成的矩阵
A
作为输入并计算输出q
。 Otherwise known as the "Extract Till You Drop" principle :) 否则称为“Extract Till You Drop”原则:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.