This question already has answers here:
Create variables with names from strings
(6 answers)
Closed 6 years ago.
I have a loop running on multiple workstations, each loop is dealing with 5 different classes, when the results is acquired it is to save the result with the name of the classes it used.
For example on workstation 1 I am using:
class1 = 1;
class2 = 10;
%code that will run on all images associated with classes 1:10
% final_result from all 10 classes is calculated here
I want to save this now, with the name such as:
result_1_10 = final_result;
save result_1_10 result_1_10;
I can do this manually but its becoming very difficult to change the values on all machines after one value is changed, I would rather it save these and pick up the numbers from the two variables class1 and class2.
Here is what I tried:
['result_' num2str(class1) '_' num2str(class2)];
This would give me result_1_10. Which is what I wanted but it is a string, rather than a variable, so I cannot assign the result value to it
['result_' num2str(class1) '_' num2str(class2)] = final_result;
Would give the error:
Error: An array for multiple LHS assignment cannot contain
LEX_TS_STRING.
I even tried str2num(num2str(class1)) but that would also give an error.
How do I actually do this?
Thank you
While you can do this, it is very much discouraged by The Mathworks themselves. Any time you are trying to store information about what a variable contains within the variable name itself, that's a sign that maybe things should be rearranged a bit. Maybe consider using a different data structure.
Consider for example using a struct where you keep the classes as fields and the result as a field.
S.class1 = 1;
S.class2 = 10;
S.result = final_result;
You could then even create an array of structs holding your data.
S = struct('class1', {1, 2, 1}, ...
'class2', {10, 11, 10}, ...
'result', {rand(10), rand(10), rand(10)});
Then you could grab all results when class1 was 1:
S([S.class1 == 1]);
Or all results when class1 as 1 and class2 was 10
S([S.class1 == 1] & [S.class2 == 10]);
If you insist on doing it the way that you've laid out, you'll have to use eval or assignin to do that. Also, sprintf is often more concise than string concatenations.
variable = sprintf('result_%d_%d', class1, class2);
eval([variable, '= final_result;']);
Related
This question already has answers here:
How to slice a struct array?
(4 answers)
Closed 2 years ago.
How can I get all values of a complete column (fieldname), for all rows, from an Octave struct?
I would get it into a cell array, or a regular vector, preferably without looping.
You seem to be confusing a few things. Partly because of your equivalence comparison of structs to "R dataframes / python pandas".
Structs are better thought of as being similar to python dicts, R lists, etc. They are a special object that can hold 'fields', which can be accessed by a 'fieldname' ( or values accessed by keys, if you prefer ).
Also, like any other object in octave, they are valid elements for an array. This means you can have something like this:
octave:1> struct( 'name', { 'Tom', 'Jim'; 'Ann', 'Sue' }, 'age', { 20, 21; 22, 23 } )
S =
2x2 struct array containing the fields:
name
age
In general, when one deals with such a struct array, accessing a field on more than one elements of the array, produces a comma separated list. E.g.
octave:6> S(2,:).name
ans = Ann
ans = Sue
This can be passed to (i.e. "expanded into") any function that expects such a comma separated list as arguments. E.g.
octave:7> fprintf( 'The girls names are %s, and %s.\n', S(2,:).name )
The girls names are Ann, and Sue.
If you want, you can also pass that list straight into a 'cell constructor', to create a cell. (though if you want it to have a particular shape, you'll have to reshape it afterwords). E.g.
octave:9> reshape( { S.age }, size(S) )
ans =
{
[1,1] = 20
[2,1] = 22
[1,2] = 21
[2,2] = 23
}
There is also struct2cell but this does something different. Try it to see what it does (e.g. C = struct2cell(S) ).
Finally, to avoid confusion, given the fact that when one deals with struct arrays, "columns" refer to columns in the 'array', I would avoid referring to "fieldnames" by that term.
I can't figure out where I am going wrong. I have a command structure (actually around 100 commands) defined in a similar manner as follows.
typedef enum bit [15:0] {
CMD_1A = 16'h1000,
CMD_1B = 16'h1100,
CMD_1C = 16'h1110,
CMD_2A = 16'h2000,
CMD_2B = 16'h2100,
CMD_2C = 16'h2200,
CMD_2D = 16'h2300,
CMD_3A = 16'h3000,
CMD_4A = 16'h4000,
CMD_4B = 16'h4010
} command_type_e;
rand command_type_e cmd_type;
Around the first # (1, 2, 3 or 4) I have a class which breaks out format. These commands have common parts while other command sections are unique. This is easy enough to control since all the valid values are defined in this typedef.
After checking valid commands defined in the list I want to check is all the undefined values so I can see how my command controller handles them and if these invalid messages get discarded correctly.
I tried to create an invalid group and constrain it to be not inside the valid types but this doesn't work.
rand bit [15:0] inv_cmd_type;
constraint not_in_range {!(inv_cmd_type inside {command_type_e});}
I tried a couple other ways without much success. I can put in specific values but that is a mess especially since that list would have to be tracked every time a new command is created.
Thoughts on how to define all the items not in that list?
Thanks!
You can create a list of all literals inside the enum using the pattern described in section 6.19.5.7 Using enumerated type methods of the 2012 LRM. Adapted to your case (and fixed formatting):
command_type_e cmd = cmd.first;
command_type_e all_cmds[$];
forever begin
all_cmds.push_back(cmd);
if (cmd == cmd.last())
break;
cmd = cmd.next();
end
Based on this list, it's trivial to create a constraint.
This question has somehow to do with an earlier post from me. See here overlap-of-nested-lists-creates-unwanted-gap
I think that I have found a solution but i can't figure out how to implement it.
First the relevant code since I think it is easier to explain my problem that way. I have prepared a fiddle to show the code:
PYFiddle here
Each iteration fills a nested list in ag depending on the axis. The next iteration is supposed to fill the next nested list in ag but depending on the length of the list filled before.
The generell idea to realise this is as follows:
First I would assign each nested list within the top for-loop to a variable like that:
x = ag[0]
y = ag[1]
z = ag[2]
In order to identify that first list I need to access data_j like that. I think the access would work that way.
data_j[i-1]['axis']
data_j[i-1]['axis'] returns either x,y or z as string
Now I need to get the length of the list which corresponds to the axis returned from data_j[i-1]['axis'].
The problem is how do I connect the "value" of data_j[i-1]['axis'] with its corresponding x = ag[0], y = ag[1] or z = ag[2]
Since eval() and globals() are bad practice I would need a push into the right direction. I couldn't find a solution
EDIT:
I think I figured out a way. Instead of taking the detour of using the actual axis name I will try to use the iterator i of the parent loop (See the fiddle) since it increases for each element from data_j it kinda creates an id which I think I can use to create a method to use it for the index of the nest to address the correct list.
I managed to solve it using the iterator i. See the fiddle from my original post in order to comprehend what I did with the following piece of code:
if i < 0:
cond = 0
else:
cond = i
pred_axis = data_j[cond]['axis']
if pred_axis == 'x':
g = 0
elif pred_axis == 'y':
g = 1
elif pred_axis == 'z':
g = 2
calc_size = len(ag[g])
n_offset = calc_size+offset
I haven't figured yet why cond must be i and not i-1 but it works. As soon as I figure out the logic behind it I will post it.
EDIT: It doesn't work for i it works for i-1. My indices for the relevant list start at 1. ag[0] is reserved for a constant which can be added if necessary for further calculations. So since the relevant indices are moved up by the value of 1 from the beginning already i don't need to decrease the iterator in each run.
I'm kind of newbie as programmer, but I wish to master Python and I'm developing open source application. This application has function to gather some information. This function takes 1 parameter. This parameter can be 0, 1 or 2. 0 = False, 1 = True, 2 = Multi. Also I have an if statement that does 2 actions. 1st - (when False) gathers single type value, 2nd - (when True) gathers multiple type values and when parameter is 2 (multi) then it will gather single type (1st) and multiple types (2nd). My if statement looks like this:
if False:
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
elif True:
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
else:
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
Is there maybe better way of avoiding this kind of coding, like in last else statement when I call both single and multiple.
Thank you in advance.
One thing I learned from Python is that although it lacks the Switch operator, you can use dictionary in a similar fashion to get things done since everything is an object:
def get_single():
# define your single function
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
def get_multi():
# define your multi function
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
actions = {
0: [get_single],
1: [get_multi],
2: [get_single, get_multi]
}
parameter = 0 # replace this line with however you are capturing the parameter
for action in actions[parameter]:
action()
This way you avoid c+p your code everywhere and have it referenced from the function, and your "actions" dictionary define the function to be used based on the parameter given.
In this case since you have multiple functions you want to call, I kept all dictionary items as a list so the structure is consistent and it can be iterated through to perform any number of actions.
Ensure you use leave out the () in the dictionary so that the functions aren't instantiated when the dictionary is defined. And remember to add () when you are actually calling the function from the dictionary to instantiate it.
This is something you will often encounter and it is pretty much always bad practice to be repeating code. Anyway, the way to do this is use two if-statements. This way, even if the first case passes, the second case can still pass. Oh, and assuming your variable that can be 0, 1 or 2 is called x, then we could either use or and two checks:
if x == 0 or x == 2:
but, personally, I prefer using in on a tuple:
if x in (0, 2):
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
if x in (1, 2):
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
There are some other questions on here that are similar but sufficiently different that I need to pose this as a fresh question:
I have created an empty class, lets call it Test. It doesn't have any properties or methods. I then iterate through a map of key/value pairs, dynamically creating properties named for the key and containing the value... like so:
def langMap = [:]
langMap.put("Zero",0)
langMap.put("One",1)
langMap.put("Two",2)
langMap.put("Three",3)
langMap.put("Four",4)
langMap.put("Five",5)
langMap.put("Six",6)
langMap.put("Seven",7)
langMap.put("Eight",8)
langMap.put("Nine",9)
langMap.each { key,val ->
Test.metaClass."${key}" = val
}
Now I can access these from a new method created like this:
Test.metaClass.twoPlusThree = { return Two + Three }
println test.twoPlusThree()
What I would like to do though, is dynamically load a set of instructions from a String, like "Two + Three", create a method on the fly to evaluate the result, and then iteratively repeat this process for however many strings containing expressions that I happen to have.
Questions:
a) First off, is there simply a better and more elegant way to do this (Based on the info I have given) ?
b) Assuming this path is viable, what is the syntax to dynamically construct this closure from a string, where the string references variable names valid only within a method on this class?
Thanks!
I think the correct answer depends on what you're actually trying to do. Can the input string be a more complicated expression, like '(Two + Six) / Four'?
If you want to allow more complex expressions, you may want to directly evaluate the string as a Groovy expression. Inside the GroovyConsole or a Groovy script, you can directly call evaluate, which will evaluate an expression in the context of that script:
def numNames = 'Zero One Two Three Four Five Six Seven Eight Nine'.split()
// Add each numer name as a property to the script.
numNames.eachWithIndex { name, i ->
this[name] = i
}
println evaluate('(Two + Six) / Four') // -> 2
If you are not in one of those script-friendly worlds, you can use the GroovyShell class:
def numNames = 'Zero One Two Three Four Five Six Seven Eight Nine'.split()
def langMap = [:]
numNames.eachWithIndex { name, i -> langMap[name] = i }
def shell = new GroovyShell(langMap as Binding)
println shell.evaluate('(Two + Six) / Four') // -> 2
But, be aware that using eval is very risky. If the input string is user-generated, i would not recommend you going this way; the user could input something like "rm -rf /".execute(), and, depending on the privileges of the script, erase everything from wherever that script is executed. You may first validate that the input string is "safe" (maybe checking it only contains known operators, whitespaces, parentheses and number names) but i don't know if that's safe enough.
Another alternative is defining your own mini-language for those expressions and then parsing them using something like ANTLR. But, again, this really depends on what you're trying to accomplish.