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

46 views (last 30 days)
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, );

Accepted Answer

Chunru
Chunru on 29 Nov 2021
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]

More Answers (1)

Walter Roberson
Walter Roberson on 29 Nov 2021
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)

Community Treasure Hunt

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

Start Hunting!