Dynamic Variable (eval=evil ? ) any other solution
이전 댓글 표시
Hello, I have to dynamically create vectors (variables) with different sizes. They will contain coordinates which will be use to evaluate given functions. I can create the variable names using eval (I have been reading people are saying eval=evil but I can't find other way around) but I could not find a way to use these vectors to evaluate given functions. For example
x=0:0.1:3 ; % Lets assume these are the coordinates
% I need to divide this coordinates into sub-coordinates using indices of x vector. in this example size of x is %(1,31) . Left and Right matrices corresponds to the x indices.
Left=[3;15;25]; Right=[12; 22; 30];
% I do this to create x vectors for each function (now it is 3)
for i=1:1:3
eval(['x_func_' num2str(i) '= x(Left(i):Right(i))']);
end
% This will create x_func_1, x_func_2 and x_func_3 vectors with x values with respect to x;
Now I want to use this sub-coordinates to evaluate functions As in Val_fun_1=sin(x_func_1), Val_fun_2=tan(x_func_2) ....., I tried to use similar eval approach but i did not work.
I have two questions.
- if eval is evil. How else I can do this? Because I need to create variables with respect to number of sub-coordinates which will change for every run.
- if there is no way out of eval, how I can do the second step. Evaluating wrt to function.
Thank you
채택된 답변
추가 답변 (1개)
Guillaume
2015년 11월 23일
Down and down the rabbit hole we go... You started using eval to generate your variables and now in order to use them you need more eval. Soon enough the whole program is just one big eval with no syntax checking, no way of debugging, no optimisation.
I'm not entirely clear on what you're trying to do, but if I understood correctly, you don't need eval at all. You just need to put your subvectors into an appropriate container. A cell array is the simplest one to use.
x = 0:0.1:3;
Left=[3;15;25];
Right=[12; 22; 30];
%see note below
subx = cell(size(Left)); %note that naming a variable xx_fun is misleading unless it contains a function handle
for i = 1:numel(Left)
subx{i} = x(Left(i) : Right(i));
end
%note: the whole code from 'see note below' can be replaced by
subx = arrayfun(@(l,r) x(l:r), Left, Right, 'UniformOutput', false);
To then use your subvectors, you can again use a loop:
funs = {@sin; @tan; @cos}; %function handles to call on respective subvector
%again see note
out = cell(size(subx));
for i = 1:numel(subx)
out{i} = funs{i}(subx{i});
end
%note, the above can be also written as
out = cellfun(@(fn, v) fn(v), funs, subx, 'UniformOutput', false);
댓글 수: 2
John D'Errico
2015년 11월 23일
I had to laugh about the rabbit hole. And quite correct too.
Stephen23
2016년 2월 23일
+1 made me laugh too!
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!