如何从 MATLAB 中的字典 return 指向结构的指针,而不是复制?

How to return pointer to struct from dictionary in MATLAB, instead of copy?

我正在将一些代码从 Python 翻译到 MatLab,我意识到它们在字典中存储元素的方式不同。比较两段代码,希望有人能证实我的看法:

在 Matlab 中,当请求字典中的值时,返回一个副本,而不是指针。因此,如果修改了该值,则字典中的值将保持不变。

在Python中,当请求字典中的值时,返回指向该对象的指针。因此,如果该值被修改,那么字典中的值也会被更改。

在 Matlab 中:

clear all; close all;  clc; 

some_dict_with_struct=containers.Map; 

some_dict_with_struct('a')=struct; 

item = some_dict_with_struct('a'); 

item.attribute = 1; 

disp(item.attribute); % displays "1" 

disp(some_dict_with_struct('a')); % has no fields? 

在Python

class A: 

  def __init__(self,a): 

    self.a=a 

    return  

A(4) 

some_dict_with_struct={} 

item = A(4) 

some_dict_with_struct['a'] = item 

print(some_dict_with_struct['a'].a)  # returns "4" 

item.a = 0 

some_dict_with_struct['a'] 

print(some_dict_with_struct['a'].a) # returns "0" 

有人可以帮我确定一个可比较的数据结构,以便在 MatLab 中使用,实现与 Python 类似的行为吗?而且,您能否确认我对行为的看法是正确的?

谢谢。

问题不在于 containers.Map,而在于它包含的项目。可以在句柄 class.

中捕获所需的行为,而不是使用 struct

在名为 Item.m 的单独文件中:


%% 

classdef Item < handle 

    properties 

        attribute = 0; 

    end 

end 

观察此行为:


some_dict_with_struct=containers.Map; 

some_dict_with_struct('a') = Item; 

item = some_dict_with_struct('a'); 

item.attribute = 1; 

disp(item.attribute); % displays "1" 

disp(some_dict_with_struct('a')); % displays "1"