0

I developed a matlab code that I now have to modify to turn into a loop. I would like to save my data at every iteration with a different variable name (without changing the variable name at the beginning of every iteration). Here I provide an example to explain what I want to do:

Matrix = rand(1000,3);
Dominated = 0;
Flag = 0;
k=0;
for k=1:10
   for i = 1:size(Matrix,1)
      Dominated = i
   end
    genvarname(sprintf('Dominated_%d',k)) = Dominated(:,:);
 end

however, if I execute this code, it does not provide me with a variable called "Domianted_1", "Domanted_2" and so on, but with a a variable called "genvarname" (replaced at every iteration) containing what was done into my code. How can I modify the code to get a different variable name at every iteration?

3
  • You don't want these variables. Save them in a matrix, a structure, or even a cell array, but don't use dynamic variable names. They are prone to errors, require hackish tools or hand-copying lines and lines of code. Commented Jun 2, 2016 at 12:07
  • @Adriaan Just because it's bad programming practice, it does not justify a downvote for the question. (In case you did that, otherwise I'm sorry for my accusation) Commented Jun 2, 2016 at 12:10
  • Your sample code sets Dominated(:,:) to 1000 on every iteration. Is this really what you want to do? If not, what will be the actual sizes of Dominated that need to be stored? Will they all be the same size? Will the size change for different values of k? Commented Jun 2, 2016 at 14:18

1 Answer 1

2

You're looking for assignin, replace:

genvarname(sprintf('Dominated_%d',k)) = Dominated(:,:);

with

assignin('base',sprintf('Dominated_%d',k),Dominated(:,:));

But I recommend to rather use structs:

allDominated.(sprintf('Dominated_%d',k)) = Dominated(:,:)
Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly. Thank you I was not aware this function existed, and I am not used to work with structs even if in this case it is perfect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.