0

I wish to change the name of col_1 to col_2, col_3....col_N for each value of 'j'. Could anyone suggest on how to handle this.? The reason why I wish to do this way is that size of col_i changes for different j. Any valuable suggestions and corrections are highly appreciated.

for j=1:N       
    for i=1:dum+1
        col_1(i,1)=x;
        col_1(i,2)=y;
    end
end
OmG
  • 18,337
  • 10
  • 57
  • 90
Gopalpur
  • 121
  • 1
  • 4
  • 14
  • Possible duplicate of [Create variables with names from strings](http://stackoverflow.com/questions/16099398/create-variables-with-names-from-strings) – RTL May 21 '17 at 14:10
  • Whilst there is an answer to the _question_ below I urge you to reconsider what the _problem_ is, or what the question _should_ be. In my opinion the problem is the fact you want to create a series of `col_x` variables with dynamically created names. There are many reasons not to do this as detailed in answers to [this question](http://stackoverflow.com/q/32467029),[this question](http://stackoverflow.com/q/2809635/52738). You may also want to check [this question](http://stackoverflow.com/q/16099398) which covers similar material. – RTL May 21 '17 at 14:23

2 Answers2

2

you can use eval like the following:

   for j=1:N       
       for i=1:dum+1
          eval(strcat(strcat('col_',num2str(j)),'(i,1)=x'));
          eval(strcat(strcat('col_',num2str(j)),'(i,2)=y'));
       end
   end
OmG
  • 18,337
  • 10
  • 57
  • 90
  • Hey, Could you pls tell for plot here. I named as following col_fs=strcat('col_',num2str(j)); inside for loop and used it to plot when it exits the inner for loop. plot(col_fs(:,1),col_fs(:,2),'r-o'). But it is throwing an error. how do i overcome this? error is "Invalid first data argument." – Gopalpur May 21 '17 at 09:49
  • The general idea in using `eval` is you must write your code in string format. Therefore, you should write the `plot` inside a string like `eval(strcat(strcat(strcat('plot(col_',num2str(j)),', col_'),"(:,2), 'r-o'"))` – OmG May 21 '17 at 09:57
  • buddy thanks alot for suggestion. It works with the following plot(eval(strcat(col_fs,'(:,j)')),eval(strcat(col_fs,'(:,j+1)')),'r-o'). – Gopalpur May 21 '17 at 10:10
  • 1
    ya. exactly. it's the another solution. – OmG May 21 '17 at 10:28
1

@KGV dynamic naming convention is not suggested in MATLAB. You have the indices already, you can call them easily. Don't try to rename/ use dynamic naming convention. You may read the below link for further information.

https://in.mathworks.com/matlabcentral/answers/105936-how-to-make-dynamic-variable-names-a1-a2-an-with-for-loop-using-eval-num2str

Siva Srinivas Kolukula
  • 1,251
  • 1
  • 7
  • 14