How to use the output of a nested function in parent function?
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I trying to make a long function readable. I was planning to write nested function inside the parent function. How can I use the output of a nested function in parent function workspace? I am getting "variable must be explicitly defined before first use" error.
%parent function
function [time_in_feeder_zone, out] = rodent_trial2(rodent, trial_no)
fn_all_data;
%nested function
function [X, Y, all_data] = fn_all_data(~)
% code
end
% 4 quadtrants based on signs
Q1 = all_data(all_data.X>=0 & all_data.Y>=0,:);
0 Commenti
Risposta accettata
Stephen23
il 8 Mar 2022
Modificato: Stephen23
il 8 Mar 2022
If you define a function with output arguments and you then want to get those outputs then of course you will also need to call the function with those output arguments. This is true for every kind of function, including nested functions.
function [..] = rodent_trial2(rodent, trial_no)
[~,~,out] = fn_all_data(); % you need to call the function with the output arguments!!!
idx = out.X>=0 & out.Y>=0;
Q1 = out(idx,:);
..
%nested function
function [X, Y, all_data] = fn_all_data() % if you defined output arguments here.
% code
all_data = .. whatever
end
end
But I suspect that you were actually attempting to share the data via the parent workspace, perhaps something like this.
function [..] = rodent_trial2(rodent, trial_no)
all_data = []; % must be defined in the parent workspace before calling nested function!
fn_all_data() % no output arguments!
idx = all_data.X>=0 & all_data.Y>=0;
Q1 = all_data(idx,:);
..
%nested function
function fn_all_data() % no output arguments!
% code
all_data = .. whatever
end
end
This is explained here: https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html#f4-73993
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Whos 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!