Dipesh
Dipesh

Reputation: 17

save in for loop matlab

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.

Upvotes: 0

Views: 265

Answers (1)

Gelliant
Gelliant

Reputation: 1845

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')

Upvotes: 1

Related Questions