Matlab:链接到变量,而不是变量值

Matlab:链接到变量,而不是变量值

问题描述:

使用google,MATLAB文档非常困难,我已经花了几个小时,而且我无法学习如何

It has been very difficult to use google, MATLAB documentation, I've spent a few hours, and I cannot learn how to

x = 1
y = x
x = 10
y

ans = 10

发生的事情是:

x = 1
y = x
x = 10
y

ans = 1

x的值存储到y中.但是我想将y的值动态更新为等于x.

The value of x is stored into y. But I want to dynamically update the value of y to equal x.

我该怎么做?

谢谢.M

Matlab具有99%的按值传递环境,这就是您刚刚演示的环境.通过引用传递的1%是句柄,要么是句柄图形(此处不相关),要么是句柄类,它们非常接近您想要的.

Matlab is 99% a pass-by-value environment, which is what you have just demonstrated. The 1% which is pass-by-reference is handles, either handle graphics (not relevant here) or handle classes, which are pretty close to what you want.

要使用句柄类执行您描述的操作,请将以下内容放入文件调用RefValue.

To use a handle class to do what you describe, put the following into a file call RefValue.

classdef RefValue < handle
    properties
        data = [];
    end
end

这将创建一个具有单独属性"data"的"handle"类.

This creates a "handle" class, with a single property called "data".

现在您可以尝试:

x = RefValue;
x.data = 1;
y = x;
x.data = 10;
disp(y.data)   %Displays 10.