automatically get the name vectors saved in the workspace in Matlab - 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.

Related

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)

How to read mat file and store in a variable

I have two .mat files. And I want to read these data of two mat files and store in variables A and B. This is my code, but I think it is not good. Can you help me store it without using matArray in matlab? (Varibale matArray is born when you call load function)
load input1.mat;
A=matArray;
load input2.mat;
B=matArray
Thank you so much
You had it right. The variable name that you have when you save the file is the name that will appear in the workspace when you load the file again. Best you can do:
load('input1.mat');
A=matArray;
load('input2.mat');
B=matArray;
clear matArray
At least you'll get the space back at the end. There is, to my knowledge, no "rename" function in Matlab...
Of course if you know what you want to name the variable when you read it in, you should save it as such:
A = matArray;
save('input1.mat', 'A');
etc
Use an output argument with the load function.
A = load('input1.mat');
B = load('input2.mat');
The two arrays will now be fields of the structures A and B:
size(A.matArray);
plot(B.matArray);
If you choose to copy these into simpler variables, or stick with your current copying approach, you should know that the copy operation is extremely efficient. When you do A = matArray; A shares the data of matArray until one of them is modified. Therefore, if you delete matArray before modifying A, no extra memory is consumed by the copy.

loading parameter files for data different sets

I need to analyse several sets of data which are associated with different parameter sets (one single set of parameters for each set of data). I'm currently struggling to find a good way to store these parameters such that they are readily available when analysing a specific dataset.
The first thing I tried was saving them in a script file parameters.m in the data directory and load them with run([path_to_data,'/parameters.m']). I understand, however, that this is not good coding practice and it also gave me scoping problems (I think), as changes in parameters.m were not always reflected in my workspace variables. (Workspace variables were only changed after Clear all and rerunning the code.)
A clean solution would be to define a function parameters() in each data directory, but then again I would need to add the directory to the search path. Also I fear I might run into namespace collisions if I don't give the functions unique names. Using unique names is not very practical on the other hand...
Is there a better solution?
So define a struct or cell array called parameters and store it in the data directory it belongs in. I don't know what your parameters look like, but ours might look like this:
parameters.relative_tolerance = 10e-6
parameters.absolute_tolerance = 10e-6
parameters.solver_type = 3
.
.
.
and I can write
save('parameter_file', 'parameters')
or even
save('parameter_file', '-struct', 'parameters', *fieldnames*)
The online help reveals how to use -struct to store fields from a structure as individual variables should that be useful to you.
Once you've got the parameters saved you can load them with the load command.
To sum up: create a variable (most likely a struct or cell array) called parameters and save it in the data directory for the experiment it refers to. You then have all the usual Matlab tools for reading, writing and investigating the parameters as well as the data. I don't see a need for a solution more complicated than this (though your parameters may be complicated themselves).

Workspace struct array input to Simulink M file S function

I would like my Simulink Level 2 S function to sequentially run a series of test cases. Each test case populates a struct containing multiple numerical arrays.
I am currently trying to achieve the above in two steps:
Step 1: generate test cases using a M file, save to Workspace as an array of structs
Step 2: read the array of structs from the Workspace into my model, using a Level 2 M
file S function to process the test cases.
Step 2 is problematic for me, in that I cannot figure out a way to get the S-function block to accept the array-of-structs variable from the Workspace as input. I want to try avoiding the simin method (another Stackoverflow discussion, here), because it seems to require representing the entire structure as a single data column, and I would like to keep the struct intact. Also tried using a Constant block with the struct array as the variable name, but that returns an 'Invalid setting for blockname parameter Value' for the block.
Would appreciate any suggestions for getting this set up correctly. Also open to a different method of building the model, if absolutely necessary. Thanks!
EDIT: Realized that I can import the data within the S function M file itself, using load. This works for the purposes of my project. However, am still interested in knowing whether a conventional solution exists for this.
If you just want to access the workspace, I would consider using evalin(caller,'expression') inside you M-file S-function:
mystruct = evalin('base','MyStructFromWorkspace');
/* (process mystruct) */
It should also do the trick.

Access a .mat file in MATLAB (without using Load function)

I have a struct (of matrices) in Matlab that has been saved on the harddisk. I currently use load to load these files inside my functions. Do you have any suggestions of doing this someother way that is much faster?
(Yes, I can pass the struct as a variable to my function but that is not possible due to memory issues!). Thanks! This would be a great help!
A = struct('local', randn(200000,14), 'usd', randn(200000,14), ...
'ttm', randn(180000,14), 'avg', randn(190000,14), ...
'ttm1yr', randn(190000,14), 'avg1yr', randn(190000,14)) ;
save('A.mat', 'A') ; clear all;clc
tic, load A.mat, A=A.local; toc %--> Takes 1.05 seconds
It appears that you're interested only in specific chunks of your saved file. I would suggest changing the format of the saved data so that individual variables can be loaded using the
S = load(filename, variables)
form of load. This will speed up the loading significantly, since you'll avoid copying all of the unwanted data from disk into memory, just to free it right away.
If your data is already in struct form, you can use this form of save (from the online docs):
save(filename, '-struct', structName, fieldNames) stores the fields of
the specified scalar structure as individual variables in the file. If
you include the optional fieldNames, the save function stores only the
specified fields of the structure. You cannot specify variables and
the '-struct' keyword in the same call to save.
Starting in R2011a you can access the contents of a Mat file without using load via the matfile object. help matfile for details.
The real advantage is that this allows read/write of portions of large arrays without loading or saving the entire array.
This is of limited use to you with your current structure, since fields of structures cannot be indexed this way. But a relatively small re-factor would allow you to take advantage of these features, depending on what the rest of your application looks like.