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?

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
Patapunfate
  • 297
  • 1
  • 4
  • 12
  • 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](http://stackoverflow.com/questions/32467029/how-to-put-these-images-together/32467170#32467170) or hand-copying lines and lines of code. – Adriaan Jun 02 '16 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) – Robert Seifert Jun 02 '16 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`? – beaker Jun 02 '16 at 14:18

1 Answers1

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(:,:)
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
  • 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 – Patapunfate Jun 02 '16 at 13:10