MATLAB execute function for multiple variables in loop -
to process data in matlab have execute function, let's call function()
. since there data processed, large array time
or voltage
(but many more) execute 1 one this:
timenew = function(time); voltagenew = function(voltage); ... etc
so done around 10 times. moreover, have such thing multiple times, resulting in around 30 lines of code same thing different variable.
is there way optimize this? using recent version of matlab (2015b) , have toolboxes installed.
a possible solution store input array struct
, them use struct input of function.
in function can identify number , content of each field using fieldnames
, getfiled
built-in function.
the function return structure
output names can made same ones of input struct.
in example below, 3 arrays generated , function siply compute square.
var_1=1:10; var_2=11:20; var_3=21:30; str_in=struct('var_1',var_1,'var_2',var_2,'var_3',var_3) str_out=my_function(str_in)
the function
function [str_out]=my_function(str_in) f_names=fieldnames(str_in) n_fields=length(f_names); i=1:n_fields x=getfield(str_in,f_names{i}) str_out.(f_names{i})=x.^2; end
hope helps.
qapla'
Comments
Post a Comment