MATLAB: Write pre-existing variable names and their values to excel

excelimporting excel datavariablevariable namexlswrite

Hi Everyone,
I have a function that outputs a ton of variables, which all have useful names and numeric values.
I want to write the existing variable name to column 1 and the associated variable data to column 2, is this possible?
I've seen some xlswrite code examples, but none where the variable name and it's data are split before entry into the xls.
Cheers Nick

Best Answer

load the data into a variable (as the load documentation states, it is a structure):
Results_Struct = load('1102 XRAIL_Z_Values.mat');
You can then get the variable names using fieldnames:
Results_Names = fieldnames(Results_Struct);
As the help and that error message tell you, the input to xlswrite must be a numeric, logical or cell array. You can easily get a cell array from the structure using struct2cell:
Results_Cell = struct2cell(Results_Struct);
Assuming that load returned a scalar structure then Results_Cell will have size px1x1, where p is the number of fields in the structure (i.e. the number of variables in the .mat file). You must ensure that the contents of each cell is a scalar: if this is not the case then you will need to deal with this in whatever way appropriate to your data. You could optionally convert this data to a numeric matrix.
You now have everything you need to call xlswrite.
Note that load-ing into a structure and using fieldnames is more efficient and less buggy than load-ing straight into the workspace and using who or whos.