Equivalent of Fieldnames function for cells - matlab

As the title says, just wondering if there is a function that works as fieldnames (http://www.mathworks.co.uk/help/matlab/ref/fieldnames.html) does, but for cells.
So if I have something like:
a = imread('redsquare.bmp');
b = imread('bluesquare.bmp');
c = imread('yellowsquare.bmp');
d = imread('greysquare.bmp');
e = {a, b, c, d};
I'm trying to retrieve either: a, b, c, d OR the image name without the extension.
I have tried fn = fileparts(e) and fntemp = cell2struct(e,2), but I can't get it working.
Hope this makes sense
Thanks

The cell array does not include any meta-information, like field name or file name. If you want access to that information you'll need to change your data storage structure. Some options include:
Scalar Structure
Good for when there is a single name to reference.
images.red = imread('redsquare.bmp');
images.blue = imread('bluesquare.bmp');
Use fieldnames(images) to get the names.
Array of structures
A little bit more general. Allows completely general names (including special characters and spaces) and additional metadata if you need it (like "size", "author")
images(1).name = 'red';
images(1).im = imread('redsquare.bmp');
images(2).name = 'blue';
images(3).im = imread('bluesquare.bmp');
Use {fieldnames.name} to get just the names.
Containers.map
Probably more than you need here, but good to know about. help comtainers.map for more.

Related

How to convert string to variable name which will be passed into plot function

How I can convert a string to a variable which will be passed into plot function?
Time = [0,1,2,3];
A = sin(Time);
B = cos(Time);
c = 2*sin(Time);
lookup = {"A", "Freq(Hz)"; "B", "Pressure(bar)", "c", "time(ms),....};
for i=1:length(lookup)
plot(Time, lookup(i,1))
ylabel(lookup(i,2))
end
I want to plot Time vs A and Time vs B and Time vs C likewise I have 50 different variables to plot.
So I planned to create the lookup with string and planned to pass as variable to plot function using eval function call.
But in few places I read that using eval is not good option so kindly suggest the alternate method.
This will solve your immediate problem:
Replace
lookup = {"A", "Freq(Hz)"; "B", "Pressure(bar)", "c", "time(ms)", ...};
with
lookup = {A, "Freq(Hz)"; B, "Pressure(bar)", c, "time(ms)", ...};
Cell arrays are heterogeneous containers, each element can be an array of any time, independently from all other types.
With this change, the rest of your code should work as intended. You might want to add a figure command or a print command inside your loop, as each plot will overwrite the previous one. figure creates a new figure window to plot in, you'll have 50 windows (not so nice). print can save the plot to a file, which might be a better approach here. Don't try to combine the 50 data lines into a single plot, it'll be a mess!
On a larger scale, you might want to rethink your strategy with defining 50 different variables. Cell arrays and struct arrays are really good ways to go about this. For example, you can think of
data.A = sin(Time);
data.B = cos(Time);
data.c = 2*sin(Time);
or
data(1).values = sin(Time);
data(1).name = "A";
data(1).units = "Freq(Hz)";
data(2).values = cos(Time);
data(2).name = "B";
data(2).units = "Pressure(bar)";
data(3).values = 2*sin(Time);
data(3).name = "c";
data(3).units = "time(ms)";
Note that, in the first case, you can also index with data.("A"), which brings you pretty close to your original idea, except that you don't have 50 variables in your workspace, but one single data structure that is easier to deal with.
Here is a very detailed list of reasons why eval can be bad to use. That link also shows some alternatives, similar to what I summarized above.

Accessing Matlab Struct Field with General Function

I'm trying to automate a process for getting information out of an array of structs.
I have the following code:
function [data] = extractData(struct,str)
data = {};
for i = 1:length(struct)
data{i} = struct(i).str;
end
The problem is that I want to provide the str value referring to a pre-determined field. In it's current form, it won't accept str and say "str is an unknown field."
The easiest way to do this would to use:
function data = extractData(struct)
str = fieldnames(struct);
data = {};
for i = 1:numel(str)
data{i} = struct.(str{i});
end
end
You may also want to consider a few different things here. First, you may want to change the name of your struct to a different name as was said above. Also you might want to look into cell arrays. Cell arrays can hold variables of different types and lengths and are easier you use.

Using "who" variable list to open cell array

I am trying to cycle through a list of variables I have say 30+ and calculate the maximum and minimum value for each column in each variable. Save this in a new array and then export to excel.
My thoughts were to use the who function to create an array with the name of all variables which are present. Then cycling through each one using a for loop after working out the size of the array which was created. This works fine, however when I try and use the string to reference the array it does not work.
I will add in the code which I have written hopefully someone will be able to come up with an easy solution :).
variable_list = who
cell2 = input('What cell size do you want to look at? ');
STARTcell = input('What was the start cell size? ');
[num_variables, temp] = size(variable_list);
for va = 1:num_variables
variable = variable_list{va}
[max_value, max_index] = max(variable{cell2/STARTcell})
[min_value, min_index] = min(variable{cell2/STARTcell})
format_values{va} = vertcat(max_values, max_index, min_value, min_index);
end
The variables I am looking at are arrays which is why I use the cell2/STARTcell to reference them.
You need to use the eval() function to be able to get the value of a variable corresponding to a string. For example:
a = 1;
b = 2;
variable_list = who;
c = eval(variable_list{2});
results in c being 2. In your code, the following line needs to change from:
variable = variable_list{va}
to:
variable = eval(variable_list{va});
resulting in variable having the value of the variable indicated by the string variable_list{va}. If variable is of cell type, then you should be fine, otherwise you may have to revise the next two lines of code as well because it seems that you are trying to access the content of a cell.

Outputting data from for loop to .mat file using numbers in title MATLAB

I need to output .mat files for the below data. I need one file to have cell (1,1) to be Mean_RPM_list1, cell (2,1) to be Mean_RPM_list2 etc. And then I need another file to have cell(1,1) to be Mean_Torque_list1 to have cell(1,1).....and so on.
Can anybody shed any light on this for me?
Also if someone knows how to automate me calling the matrices A and B so I could have A = [Mean_rpm1:Mean_rpmMAX], that would also be very helpful.
TIA for any help.
A = [Mean_rpm1 Mean_rpm2 Mean_rpm3 Mean_rpm4 Mean_rpm5 Mean_rpm6 Mean_rpm7 Mean_rpm8 Mean_rpm9 Mean_rpm10 Mean_rpm11 Mean_rpm12];
B = [Mean_torque1 Mean_torque2 Mean_torque3 Mean_torque4 Mean_torque5 Mean_torque6 Mean_torque7 Mean_torque8 Mean_torque9 Mean_torque10 Mean_torque11 Mean_torque12];
plot(A,B,'*')
for i = 1:num_bins;
bin = first + ((i-1)/10);
eval(sprintf('Mean_RPM_list%0.f = A;',bin*10));
eval(sprintf('Mean_Torque_list%0.f = B;',bin*10));
end
First of all this is really bad idea to create a set of variables with names different by numbers. As you can see it's very difficult to deal with such variables, you always have to use eval (or other related) statements.
It's much easier to create a cell array Mean_rpm and access its elements as Mean_rpm{1}, etc.
If the vectors are numeric and have the same size you can also make a 2D/3D array. Then access as Mean_rpm(:,:,1) etc.
Next, to store a cell array to a mat-file you have to create this array in MATLAB. No options (at least for now) to do it by parts in a loop. (But you can do it for numeric vectors and matrices using matfile object.) So why do you need this intermediate Mean_RPM_list variable? Just do Mean_RPM_list{bin*10} = A in your loop.
For your first question, if you already have those variables you have to use eval in a loop. Something like
A = [];
for k=1:K
eval(sprintf('A{k} = [A, Mean_rpm%d];',k));
end
You can also get names for all similar variables and combine them.
varlist = who('Mean_rpm*');
A = cell(1,numel(varlist);
for k = 1:numel(varlist)
eval('A{k} = varlist{k};');
end
Here is one without loop using CELL2FUN:
A=cellfun(#(x)evalin('base',x),varlist,'UniformOutput',0);
You should avoid having all these individual variables around in the first place. Data types like arrays, cell arrays and structure arrays exist to help you with this. If you want each variable to be associated with a name, you can use a structure array. I've made an example below. Instead of assigning a value to Mean_rpm1 like you are doing now, assign it to meanStruct.Mean_rpm1 then save the entire structure.
% as you generate values for each variable, assign them to the
% appropriate field.
meanStruct.Mean_rpm1 = [10:10];
meanStruct.Mean_rpm2 = [12:15];
meanStruct.Mean_rpm3 = [13:20];
meanStruct.Mean_rpm4 = [14];
meanStruct.Mean_rpm5 = [15:18];
meanStruct.Mean_rpm6 = [16:20];
meanStruct.Mean_rpm7 = [17:22];
meanStruct.Mean_rpm8 = [18:22];
meanStruct.Mean_rpm9 = [19:22];
meanStruct.Mean_rpm10 = [20:22];
meanStruct.Mean_rpm11 = [21:22];
meanStruct.Mean_rpm12 = [22:23];
% save the structure array
save('meanValues.mat','meanStruct')
% load and access the structure array
clear all
load('meanValues.mat')
temp = meanStruct.Mean_rpm3

Matlab dynamic fieldnames structure with cell arrays

How can i access the following structure path with dynamic fieldnames:
var = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text';
fields = textscan(var,'%s','Delimiter','.');
refxtree.(fields{:}) does not work because MaterialStreamObjects contains a cell array of which I want to access the 8th cell and then continue down the structure path.
In the end I want to get and set the fieldvalues.
You need to build the appropriate input to subsref, possibly using substruct. Look at the MATLAB help.
You can define an anonymous function to navigate this particular kind of structure of the form top.field1.field2.field3{item}.field4.field5.field6.field7 (as an aside: is it really necessary to have such a complicated structure?).
getField = #(top,fields,item)top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}).(fields{7})
setField = #(top,fields,item,val)subsasgn(top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}),struct('type','.','subs',fields{7}),val);
You use the functions by calling
fieldValue = getField(refxtree,fields,8);
setField(refxtree,fields,8,newFieldValue);
Note that fields is required to have seven elements. If you want to generalize the above, you will have to dynamically create the above functions
In this case, it is easier to just use EVAL:
str = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text';
%# get
x = eval(str)
%# set
evalc([str ' = 99']);