Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear base workspace variable from within function

Tags:

matlab

With the following code I've added variables into the base workspace:

function data_startup()
bdclose all;
data=load(fullfile('B', 'C', 'data.mat')); 
file_variables=fieldnames(data);% get the field names as cell array
for ii=1:length(file_variables)
     assignin('base', file_variables{ii}, data.(file_variables{ii}));
end

Now, I would like to clear variables from the base workspace, I've tried :

evalin('base','clear file_variables');

But this is not working :(

like image 215
lola Avatar asked Jun 26 '26 07:06

lola


1 Answers

You're trying to clear the variable with name file_variables, which probably doesn't exist. What you want is:

evalin('base',['clear' sprintf(' %s',file_variables{:})]);

If you want to understand what's going on: run and debug this line in your function, then inspect the outcome of

['clear' sprintf(' %s',file_variables{:})]

which will be the command run by evalin.

More info:

[a b c] concatenates the strings in a,b and c, because the strings themselves are 1xN arrays.
{:} returns the cell array as a comma separated list which is then inputted to sprintf, more info on this here.

like image 113
Gunther Struyf Avatar answered Jun 29 '26 03:06

Gunther Struyf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!