简体   繁体   English

从 matlab 工作区打印到 C 文件 - 获取变量的名称

[英]Printing from matlab workspace to a C file - getting names of the variable

I am generating a C header file from Matlab using the Matlab workspace variables.我正在使用 Matlab 工作区变量从 Matlab 生成一个 C header 文件。 For that I am using a vector of the matrices, each matrix corresponds to one.h file.为此,我使用矩阵的向量,每个矩阵对应一个.h 文件。 I need the variables' names for changing the comments/filenames based on the usage of a particular matrix in a loop.我需要变量的名称来根据循环中特定矩阵的使用来更改注释/文件名。

So I would have:所以我会:

matrix = {A, B, C};

for any_matrix = matrix
   fprintf(file, '#ifndef %s_INCLUDED\n#define %s_INCLUDED\n\n', variable_name, variable_name)
   ...
   % rest of the code using the values of the variables
end

How can I access the information about the variable name to put it in the placeholder?如何访问有关变量名的信息以将其放在占位符中?

It is not possible to get the name of a variable in a context such as this.在这样的上下文中获取变量的名称是不可能的。 But if you reverse your logic, you can get there: list the names of the variables you want to export, then in the loop fetch the value of each of those variables.但是如果你反转你的逻辑,你可以到达那里:列出你想要导出的变量的名称,然后在循环中获取每个变量的值。

eval is considered bad practice , but in a use case like this it is actually really useful. eval被认为是不好的做法,但在这样的用例中它实际上非常有用。

This is how I'd do it:我就是这样做的:

variables = ["A", "B", "C"];
for name = variables
   value = eval(name);
   % use `name` and `value` here.
end

If this is a function, and you call the function with export_my_vars(["A", "B", "C"]) , then you won't have access to those variables and eval will fail.如果这是一个 function,并且您使用export_my_vars(["A", "B", "C"])调用 function,那么您将无法访问这些变量并且eval将失败。 In this case, use evalin(...,'caller') instead.在这种情况下,请改用evalin(...,'caller')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM