Eric
Eric

Reputation: 429

Evaluate a variable from a function and assign the new variable into base Workspace

I have a GUI that takes users typed-in equations such as delta_P=C1-C2;velocity=diff(y)./diff(x); all in one string delimited and terminated by ;. Then, within the GUI function, I pull in C1, C2, x, and y in and I want to evaluate to generate delta_P and velocity and assign them into the base Workspace. My problem is I don't know delta_P and velocity ahead of time so that I can't just do:

assignin('base','delta_P',C1-C2);

I need to break down the string to identify the new variable names left of the equal signs and assign to them what are right of the equal signs into the base Workspace?

I condition an input string with one or more statements so that there is no space and no carriage return. Then, I tried the following:

str_in = 'delta_P=C1-C2;velocity=diff(y)./diff(x);'
str_sp = strsplit(str_in,';');
str_sp = str_sp(1:end-1); % last ';' results in an empty char

Then, this is where I get lost:

cellfun(@(c1,c2)assignin('base',c1(1:c2-1),c1(c2+1:end)),str_sp,cellfun(@(c)strfind(c,'='),str_sp,'uni',0),'uni',0);

  1. It just doesn't look efficient
  2. It still doesn't work as c1(c2+1:end) is also a string
  3. I tried eval(c1(1:c2-1)), but MATLAB complains C1,C2,x, and y are undefined.

Thanks.

Upvotes: 2

Views: 311

Answers (1)

Paolo
Paolo

Reputation: 26074

You should evaluate the expression in the current workspace, and then evaluate the assignment in the base workspace.

Here's an example function which illustrates the logic:

function q61401249
  C1 = 1;
  C2 = 2;
  x = [1 1 2];
  y = [2 3 4];

  str_in = 'delta_P=C1-C2;velocity=diff(y)./diff(x);';
  str_sp = strsplit(str_in,';');
  str_sp = str_sp(1:end-1);

  for i = 1:length(str_sp)
     s = split(str_sp(i),'=');
     assignin('base',s{1},eval(s{2}));
  end
end

when you run the function, you will see that two new variables have been created in the base workspace, delta_P and velocity as desired.

Of course the assumption here is that the equation is well formed, for instance that there aren't two = signs.

Upvotes: 1

Related Questions