how to deal with changing array name through function in matlab
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Hello I'm writing a function and passing a matrix name in the body of the function I need to use that name that I passed in a for loop as follows:
function FileFeatures=getFeatures(Filename)
for i=2:9
MAVf(i-1)= MAV( Filename(:,i ));
end
I tried something like using eval but it doesn't work it works in the command line without passing the parameter and once I pass it it gives me Error using eval Undefined function or variable
here is what I have tried :
function FileFeatures=getFeatures(Filename)
signal=eval(Filename);
for i=2:9
MAVf(i-1)= MAV( signal(:,i ));
end
Any suggestions? and Thank You for your time
4 Commenti
Ced
il 17 Mar 2016
Maybe my answer does not make sense then. Which of the two is correct?
a) You want to pass the name of a Variable, and extract that value
b) You want to pass the name of a Variable, and create a new variable with that name.
Risposte (1)
Ced
il 17 Mar 2016
This is not going to work. The reason is that your variable exists in a different workspace. As soon as you pass into a function, you enter the function workspace, which knows nothing about the variables existing in the other workspace.
To my knowledge, there is no possibility to "steal" the variable from a caller workspace (i.e. the workspace one level "higher"). It is however possible to have the function share workspaces. You can e.g. use nested functions, or use assignin. See the documentation for examples.
There is however function in Matlab 2016 called "getVariable" which might allow to do what you want. It's made for simulink to fetch variables from other workspaces. I don't have 2016, but maybe you can test it if you do. If it works, I would expect it to work something like this:
function eval_var_by_name_basews()
a = 2;
name = 'a';
eval_var_by_name(name)
end
function eval_var_by_name( variable_name )
signal = getVariable('caller',variable_name);
disp(signal)
end
This being said, as Guillaume pointed out, I cannot think of a reason to do this. One little workaround is the following:
1. Save your variables in a struct
2. Now, pass both the struct and the variable name to the function
Example:
% the main function
function pass_struct_main()
my_struct = struct;
my_struct.a = 2;
my_struct.b = 4;
my_struct.c = 6;
name = 'a'; % name of the variable you want
eval_struct_field_by_name( my_struct, name )
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The called function
function eval_struct_field_by_name( my_struct, name )
value = my_struct.(name);
disp(value)
end
Hope this helps clear things a bit.
0 Commenti
Vedere anche
Categorie
Scopri di più su Install Products in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!