简体   繁体   中英

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. For that I am using a vector of the matrices, each matrix corresponds to one.h file. 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.

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. In this case, use evalin(...,'caller') instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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