How to avoid error when whether the function has returns is unknown?
Ältere Kommentare anzeigen
function Output = PairArrayArrayfun(Function,Array1,Array2,ArrayDimension,UniformOutput)
CatDimension=max(ndims(Array1),ndims(Array2))+1;
Output=cellfun(@(Cell)Function(Cell{1},Cell{2}),PackIntoCell(cat(CatDimension,SplitIntoCell(Array1,ArrayDimension),SplitIntoCell(Array2,ArrayDimension)),CatDimension),"UniformOutput",false);
if UniformOutput
Output=cell2mat(Output);
end
end
My function accept a parameter "Function", which is expected to be a function pointer offered by the caller. However, I don't know whether this caller-offered function has any returns. In my current code, if the given function returns nothing, an error will occur.
I want my function to return nothing if the caller's function returns nothing; to return something if the caller's function returns something. How should I code?
Try-catch is a bad idea since the caller's function will be called for more than expected times. This may cause more issues if the given function has side effects.
The given function in the usecase is very likely to be anonymous, so nargout(Function) will always return -1.
The built-in function cellfun should face the same issue, and MATLAB developers successfully solved it. However, its source code is unavailable.
Akzeptierte Antwort
Weitere Antworten (2)
You can use nargout(Function) to check the number of output arguments. <https://www.mathworks.com/help/matlab/ref/nargout.html>
4 Kommentare
埃博拉酱
am 29 Okt. 2019
Walter Roberson
am 30 Okt. 2019
In my opinion it is a bug in the function design to define a varargout function that returns no output if requested by the user. That said, I have seen it in a couple of Mathworks functions.
Walter Roberson
am 30 Okt. 2019
0 Stimmen
try/catch the first execution outside of the cellfun. If the assignment works then cellfun the rest of the iterations. If it fails then you will need to loop instead of cellfun.
cellfun cannot be used with functions that produce no output.
1 Kommentar
埃博拉酱
am 30 Okt. 2019
Kategorien
Mehr zu Graphics Object Programming finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!