Write file(s) with all properties of a MATLAB model

2 ビュー (過去 30 日間)
the cyclist
the cyclist 2022 年 8 月 31 日
コメント済み: Walter Roberson 2022 年 8 月 31 日
Suppose I have built a machine learning model in MATLAB. It has a list of properties (and underlying property data) that encapsulates the model. For example ...
% Set seed for reproducibility
rng default
% Number of observations and features
N_obs = 20;
N_feat = 5;
% Generate some made-up data
x = randn(N_obs,N_feat);
y = randn(N_obs,1);
% Fit a model, and get the properties
mdl = fitrtree(x,y);
modelProperties = sort(properties(mdl));
% Display a few properties
modelProperties(1:3)
ans = 3×1 cell array
{'BinEdges' } {'CategoricalPredictors'} {'CategoricalSplit' }
I would like to share the property values (not just the property names) with a non-MATLAB user. I'm looking for a clever way to write the values to a text file.
The main stumbling block is that the properties are of many different data types, so I cannot just loop through them and use a single function (e.g. writecell) to write to file. It seems I will need to hard-code a switch statement or the like, to find the appropriate function to write each data type appropriately.
Am I overlooking a more elegant method?
  2 件のコメント
Walter Roberson
Walter Roberson 2022 年 8 月 31 日
struct() and jsonencode()?

サインインしてコメントする。

回答 (1 件)

Abderrahim. B
Abderrahim. B 2022 年 8 月 31 日
Hi!
I prefer to use fprintf with fopen and fclose. Once you learn how to design formatSpecifications you will always use fprintf instead of other data writing functions.
You have a cell,, suggest to convert to table, then you write row by row.
Hope this helps
  1 件のコメント
the cyclist
the cyclist 2022 年 8 月 31 日
編集済み: the cyclist 2022 年 8 月 31 日
I appreciate the response, but I don't think you quite understood the depth of the issue. Maybe I didn't give enough detail.
Yes, the property names are a cell, and it would be trivial to write that cell to file, using either the generic fprintf function or a more specific one like writecell.
But that is not what I am doing. Rather, I need to write the underlying data values for each property. For example, I want to write the property values for "PredictorNames"
mdl.('PredictorNames')
ans =
1×5 cell array
{'x1'} {'x2'} {'x3'} {'x4'} {'x5'}
which is itself a cell array, but other property values might be a numeric array:
mdl.('X')
ans =
0.5377 0.6715 -0.1022 -1.0891 1.4193
1.8339 -1.2075 -0.2414 0.0326 0.2916
-2.2588 0.7172 0.3192 0.5525 0.1978
0.8622 1.6302 0.3129 1.1006 1.5877
...
So, via your method, I am still stuck with writing a separate format specification for each property, which is exactly what I am trying to avoid.
(I truly think there is no way around this, but a guy can hope.)

サインインしてコメントする。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by