create a ndgrid given based on string variable input

3 views (last 30 days)
Hi there. Let's start say I'm given a 1x2 cell list..
t={'x1','x2'} % and
T = upper(t) % upper case of t
After this I've defined x1 and x2 with the eval function
eval([t{1} '= 1:1:10;'])
eval([t{2} '= 1:1:10;'])
How do I create a meshgrid [X1,X2]=meshgrid(x1,x2) from the cell 'T'? If 't' can be any length of 1:3 and could be any combination of x1, x2 and x3 for example
t={'x2','x3'} % x1 is a constant want -> [X2,X3]=meshgrid(x2,x3)
t={'x1','x3'} % x2 is a constant want -> [X1,X3]=meshgrid(x1,x3)
t={'x1','x2','x3'} % want to create 3D mesh (no constants) -> [X1,X2,X3]=meshgrid(x1,x2,x3)
t={'x3'} % no mesh just X3=x3 (x1 and x2 are constants)
I hope this makes sense. Just to recap my cell vector 't' is generated from my previous code and gives which what x# is required and sets up the meshing with eval.
I'll explain further if required thanks,

Accepted Answer

Guillaume
Guillaume on 30 Jan 2015
Well, using dynamically named variables is not recommended for exactly this reason. You end up peppering your whole code with eval everywhere (and you lose syntax checking, speed optimisation, ease of debugging). So the first question is: do you actually need dynamically named variables? Can't you use cell arrays, n-d matrices, or other type of containers and avoid this headache?
If you can't, I'd create a subfunction in which you can use assignin and evalin, instead of eval, for cleaner code:
function ndgridvar(varnames)
%varnames: a cell array of variable names that exist in the calling function
%the function creates variables with the same names by capitalised in the caller workspace
%get values of variables into a cell array, normally I'd use cellfun
%but you can't use evalin in an anonymous function
inputs = cell(size(varnames));
for v = 1:numel(varnames)
inputs{v} = evalin('caller', varnames{v});
end
%create output cell array
outputs = cell(size(varnames));
%call ndgrid
[outputs{:}] = ndgrid(inputs{:});
%assign to variables into caller, again can't use cellfun
for v = 1:numel(varnames)
assignin('caller', upper(varnames{v}), outputs{v});
end
end
  1 Comment
Joseph
Joseph on 31 Jan 2015
That is great. Thank you. Noted regarding your comment on dynamic variables!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!