How can i use string values saved in a cell array as variable names in a for loop.

11 次查看(过去 30 天)
I would like to use a cell array string value as a variable name in a for loop. So every iteration there would a new variable created from the cell string value. also is it posible the change/append some text to the variable name each iteration. I think its much easier to look at the code and see what i'm trying to acomplish.
Dist_type = {'Kernel', 'Gamma', 'Normal', 'Weibull', 'Stable', 'Logistic', 'GeneralizedExtremeValue'};
p = '_pdf';
c = '_cdf';
for i = 1 : numel(Dist_type)
dis_obj = fitdist(testData, Dist_type{:,i});
% Generate pdf and cdf values and assign them to variables j and k
j= pdf(dis_obj, testData);
k= cdf(dis_obj, testData);
% Somehow rename j and k to the specific dist_type name and append p = "_pdf" and c = "cdf" at the end. As an example in the
% first iteration the two variables created would be "kernel_pdf" and "Kernel_cdf" so
% this loop would generate a separate pdf and cdf for each distribution type.
% j = append(Dist_type{:,i},p);
% k = append(Dist_type{:,i},c);
% Combine testData with each pdf and cdf values into a table
% j = table(testData, );
% k = table(testData, );

采纳的回答

Chunru
Chunru 2021-11-29
You can put the result in a struct with field names corresponding to your Dist_type
load Test_Data.mat
Dist_type = {'Kernel', 'Gamma', 'Normal', 'Weibull', 'Stable', 'Logistic', 'GeneralizedExtremeValue'};
p = '_pdf';
c = '_cdf';
for i = 1 : numel(Dist_type)
dis_obj.(Dist_type{i}) = fitdist(testData, Dist_type{i});
end
Warning: Maximum likelihood estimate of the shape parameter ALPHA has converged to a boundary point.
Confidence intervals and standard errors can not be computed reliably.
dis_obj
dis_obj = struct with fields:
Kernel: [1×1 prob.KernelDistribution] Gamma: [1×1 prob.GammaDistribution] Normal: [1×1 prob.NormalDistribution] Weibull: [1×1 prob.WeibullDistribution] Stable: [1×1 prob.StableDistribution] Logistic: [1×1 prob.LogisticDistribution] GeneralizedExtremeValue: [1×1 prob.GeneralizedExtremeValueDistribution]

更多回答(1 个)

Walter Roberson
Walter Roberson 2021-11-29
We recommend against that.
Instead, use normal variable names in your loop, but when you generate your table() then use the 'VariableNames' property to set the name of the columns as required.
If you want to create a number of these tables, then either put them into a cell array, or put them as fields in a struct (using dynamic field names)

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by