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

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", ...
"rewardconcentration4"];
uniqueFeature = {'uniqueCost1','uniqueCost2','uniqueCost3', ...
'uniqueReward1','uniqueReward2','uniqueReward3','uniqueReward4'};
for ii = 1:numel(feature)
% some code
uniqueFeature{ii} = unique(noNaNcleanedData);
end
I want to assign the result of each iteration to the variable names in 'uniqueFeature' cell array. How can I do it?

 Accepted Answer

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.

5 Comments

Thank you for your comment! Yes, I am familiar with this post. I was trying to assign the results of each iteration with the aforementioned variable names in some other way. The names of the variables I want give are not necessarily one integer different anyway.
What benefits do you see in using run-time variable names in your assignments? You would need to use run-time variable names to access the results. What about your situation makes it unsuitable for using a cell array, or using dynamic field names in a struct ?
Don't make them stand-alone variables. Make them fields of a struct array or variables inside a table array.
names = ["apple", "banana", "cherry", "quit"];
S = struct;
T = table;
for whichone = 1:numel(names)
N = names(whichone);
S.(N) = whichone.^2;
T.(N) = whichone.^3;
end
S
S = struct with fields:
apple: 1 banana: 4 cherry: 9 quit: 16
T
T = 1×4 table
apple banana cherry quit _____ ______ ______ ____ 1 8 27 64
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.
Got it. Thank you very much!

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2022a

Asked:

on 28 Jul 2022

Commented:

on 29 Jul 2022

Community Treasure Hunt

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

Start Hunting!