0

I am trying to save variables in a for loop. The following new variable can be created:

eval(['C' num2str(j) '=B']);

But I get an error while using this to save the variable by the following command :

save([dataDir, files(j).name],eval(['C' num2str(j) '=B']),'-append')

The error is : (Error: The expression to the left of the equals sign is not a valid target for an assignment.).

I wonder what is wrong with my approach and how can I save the changing variable name in changing file name in a for loop.

I will greatly appreciate your assistance.

Ebrahim Poursadeqi
  • 1,776
  • 2
  • 17
  • 27
Dipesh
  • 17
  • 5
  • 1
    Please don't do this. Dynamical variable names are a plague on humanity. – Andras Deak -- Слава Україні Jul 05 '17 at 19:36
  • Well, I did read the caveats in the mathworks Q&A forums about that. But, I wonder what exact harm will it cause in above case. Will I escape the plague ? – Dipesh Jul 05 '17 at 19:41
  • 1
    Once you start using `eval` to create dynamically named variables, you'll always need `eval` to use them later, which is a bloody mess. The secret ingredient that most people miss are structs which [can be addressed dynamically](https://stackoverflow.com/a/40226542/5067311). You have the freedom to use dynamic strings to access your variables (e.g. `data_struct.(['C' num2str(j)])` in your case), but you can avoid `eval` and your code will stay more readable. For interactive use, you type `data_struct.C15243` instead of `C15243`...not a huge loss. – Andras Deak -- Слава Україні Jul 05 '17 at 19:49
  • Or just use multidimensional arrays (assuming variables of the same size), or cell arrays (if they're not). – beaker Jul 05 '17 at 19:49
  • 1
    @Dipesh The harm it will cause is directly that it will slow down your program considerably, and indirectly that you affine yourself with a coding style prone to unreadability and hard-to-debug errors. Please read [this answer of mine](https://stackoverflow.com/a/32467170/5211833) and the references contained therein to read up on the root cause of this. – Adriaan Jul 05 '17 at 20:14

1 Answers1

1

There is an equal sign in your eval statement.

Can't you just save B? do not use eval in a function itself.

save([dataDir, files(j).name],B,'-append')

Otherwise I would recommend storing the variable name itself

varname = sprintf('C%.0f',j)
eval([varname,'=B']);
save([dataDir, files(j).name],varname,'-append')
Gelliant
  • 1,835
  • 1
  • 11
  • 23
  • Well, I know I can. But I want a tag with the variable which will allow me to identify it later. That is why I need to concatenate the changing 'num2str(j)' to C ( or any other named variable) to save it. – Dipesh Jul 05 '17 at 18:24
  • You could just remove `'=B'` from the part of your code that should save C. – Gelliant Jul 05 '17 at 18:27