dynamic variable names in matlab - matlab

I wish to expand a structure (bac) with a number of fields from another structure (BT). The names of these fields are contained in the cell array (adds) as strings.
this is what i have now (and obviously doesn't do the job, explaining this post):
for i=1:numel(adds)
eval(genvarname('bac.',adds{i})) = eval(strcat('BT.',adds{i}));
end
I also tried using sprintf, which did not seem to work for me. I feel confident one of you knows how to do it, since I feel it should be rather easy.

The best way of doing this is to use dynamic field names:
for i=1:numel(adds)
bac.(adds{i}) = BT.(adds{i});
end

Related

Change a Variable's Name in Matlab's Workspace

I have a problem that has more than likely been asked before but I have yet to find a solution that works for me.
I would like to know if it's possible to change the name of variable within a workspace in Matlab?
The need for this is a follows,
I have a small section of code that imports over 60's columns of data from Excel into Matlab, each column has over 10,000 rows in, so a fair amount of data. Row 1 of each column is the variable, i.e. R1C1 = "Time from X to Z" I would like to know if its possible for Matlab to create a Variable called "Time_from_X_to_Z" then store all the data in that Variable from the excel sheet. I am able to store all the data in separate variables, I just need a bit of help naming the variable.
I would like to name the variables like so, as when I come to re-use the code the order of the column may change from time to time, hence why I can't just let Variable1 = Varibale1 etc.
Here is some of the code I have tried from my research.
VariableName = txt(1,i);
VariableName = num2str(cell2mat(VariableName));
VariableName = Variable
clear Variable
This was my most successful one but is nowhere near what I expected it to be.
I hope that all makes sense.
Thanks for any help you are able to provide.

Define variables in loops using loop indicies [duplicate]

I have a process which is repeated on a set of data stored in separate folders. Each time a certain folders data is processed I need new variable names as I need to results separate after the initial processing is finished for more processing.
For example at the start of each new block of the repeated function I declare sets of arrays
Set_1 = zeros(dim, number);
vectors_1 = zeros(dim, number);
For the next set of data I need:
`Set_2 = .........`
and so on. There is going to be alot of these sets so I need a way to automate the creation of these variables, and the use the new variables names in the function whilst maintaining that they are separate once all the functions are completed.
I first tried using strcat('Set_1',int2str(number)) = zeros(dim, number) but this does not work, I believe because it means I would be trying to set an array as a string. I'm sure there must be a way to create one function and have the variables dynamically created but it seems to be beyond me, so it's probably quite obvious, so if anyone can tell me a way that would be great.
I'd not do it like this. It's a bad habit, it's better to use a cell array or a struct to keep multiple sets. There is a small overhead (size-wise) per field, but it'll be a lot easier to maintain later on.
If you really, really want to do that use eval on the string you composed.
The MATLAB function genvarname does what you want. In your case it would look something like:
eval(genvarname('Set_', who)) = zeros(dim, number);
However, I would follow the recommendations of previous answers and use a cell or struct to store the results.
This sort of pattern is considered harmful since it requires the eval function. See one of the following for techniques for avoiding it:
http://www.mathworks.co.uk/support/tech-notes/1100/1103.html
http://blogs.mathworks.com/loren/2005/12/28/evading-eval/
If you insist on using eval, then use something like:
eval(sprintf('Set_1%d = zeros(dim, number);', number))

LibreOffice, Using Constants as query Parameters

I'm using the VLOOKUP function to move data from one table into another. I need to apply this formula to an entire column, and I need to know how to define certain parameters as variable and some as constant.
Here's my problem:
=VLOOKUP($D8,Sheet2.A1:B20,2)
becomes, when I drag the corner of the cell across multiple rows,
=VLOOKUP($D8,Sheet2.A1:B20,2)
=VLOOKUP($D9,Sheet2.A2:B21,2)
=VLOOKUP($D10,Sheet2.A3:B22,2)
=VLOOKUP($D11,Sheet2.A4:B23,2)
And what I need is
=VLOOKUP($D8,Sheet2.A1:B20,2)
=VLOOKUP($D9,Sheet2.A1:B20,2)
=VLOOKUP($D10,Sheet2.A1:B20,2)
=VLOOKUP($D11,Sheet2.A1:B20,2)
With the first parameter changing and the rest remaining constant. I'm sure there is an easy way to do this, but searching and browsing help topics is returning nothing. I admittedly have zero background in spreadsheets. Thanks for your help
Add more $ signs, like this:
=VLOOKUP($D8,Sheet2.$A$1:$B$20,2)
https://help.libreoffice.org/Calc/Addresses_and_References,_Absolute_and_Relative

automatically get the name vectors saved in the workspace in Matlab

I have multiple vectors (+100) that have been loaded into MATLAB workspace, I would like to write a script that can plot and save them all, but for that I need their name, my question is: is there a way to automatically get the name vectors saved in the workspace.
thanks in advance.
Step one: whoever gave you a *.mat file with 100+ named variables in it, [censored for strong language and scenes some viewers may find upsetting]. I am only partly joking here; if you find yourself in this sort of situation normally it is because something has gone terribly wrong upstream. We can work around it, though.
Step two: use who with the filename to get a list of variables in that file
names = who('-file', 'all');
Step three: load the variables (or a subset of them) into a struct
data = load('all.mat');
Step four: use dynamic structure naming to extract data:
for n = 1:length(names);
plot(data.(names{n})); % or whatever you want to do with this data
end
I would probably just use the loop to dump the data in a cell array so as to make further processing simpler and avoid further use of dynamic field names or worse, eval.
You can use who, which lists all variables alphabetically in the active workspace.

Accessing values in multiple structures with similar names

I'm reasonably new to Matlab, and have been trying to teach myself. I have looked for a similar question, but can't find one that's quite right.
In my workspace I have several structures with similar names. These structures will always start with the same word ('Base'), though the rest of the name will change ('1', '2', '3'), so for example Base1, Base2, Base3... etc. These variables were generated using the data cursor tool in a figure, so contain the fields Target, Position and DataIndex. I am only interested in the value in Base*.Position(1,1). I would like to extract this value from each structure, as many times as there are structures (in one instance there may be 6 structures, another time only 4).
I am considering using the eval function, but it seems to work on exact strings rather than only the first part of a name. Additionally, a lot of documentation seems to advise against using eval.
So far I have:
clearvar except 'Base*'
list_variables=who;
for i=1:length(list_variables)
BaseTS(i) = eval('Base1.Position(1,1)');
end
It's the for loop I'm stuck on, as I don't know how to generalise so it will extract the value .Position(1,1) for each different structure name.
Thanks in advance
Instead of having many structures called Base1, Base2 etc rather put your structure in an array. Then you could rather call Base(1).Position(1,1), Base(2).Position... etc. Your code will be more flexible and manageable this way.
So I suggest when you export using the data cursor, export to a variable called Base_temp and then immediately stick this into the next element of an array:
Base(end+1) = Base_temp
or even:
Position(end+1) = Base_temp.Position(1,1);
Then it's just a case of pressing up and enter after each time you export with the data cursor.
What you have read about avioding eval is correct, it's very rare (if ever) that eval is a good idea. It makes your code hard to read and very hard to debug. But since you're learning, this is how you could fix your loop. (But don't do this way, seriously don't, use arrays rather):
for i=1:length(list_variables)
BaseTS(i) = eval(['Base', num2str(i), '.Position(1,1)']);
end
in other words use string concatenation to build up your string and use the looping variable (i) to get the different numbers. You'll need num2str to convert fromthe number to the string. But don't do it this way. This is a bad way.
Dan's suggestion about avoiding eval is very valid. But if you decide to keep on the structures you have in your workspace, here's something without loops, but again cellfun seems to use loops internally. So, I guess this could be an alternative solution, with the not-so-popular eval -
list1 = who('Base*')
list2 = cellstr(strcat('BaseTS(',num2str([1:numel(list1)]'),')='));%%//'
ev1 = strcat(list2,list1,'.Position(1,1)');%%//'
cellfun(#evalc,ev1,'uni',0)