Clear Filters
Clear Filters

How do I assign result array of a loop to a variable name?

3 views (last 30 days)
I have a for loop which gives an one dimensional array in each iteration. (i.e. [1;2;3;4]) But they could be different in length. The example code is given below.
feature = ["intensityofcost1","intensityofcost2","intensityofcost3", ...
"rewardconcentration1","rewardconcentration2","rewardconcentration3", ...
uniqueFeature = {'uniqueCost1','uniqueCost2','uniqueCost3', ...
for ii = 1:numel(feature)
% some code
uniqueFeature{ii} = unique(noNaNcleanedData);
I want to assign the result of each iteration to the variable names in 'uniqueFeature' cell array. How can I do it?

Accepted Answer

Steven Lord
Steven Lord on 28 Jul 2022
Can you dynamically create variables with numbered names like uniqueCost1, uniqueCost2, uniqueCost3, etc.? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.
Struggling in MATLAB
Struggling in MATLAB on 29 Jul 2022
I think it would increase the readability of my script. Else I always have to refer back to the array name container uniqueFeature to see which variable I am dealing with.
Besides, I am generally curious about how people do it.

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!