Kim
Kim

Reputation: 37

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?

Upvotes: 0

Views: 77

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60660

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.

Upvotes: 0

Related Questions