MATLAB: How to return two results by one output when using arrayfun()

arraryfun; return;

f=@(X) fun1(x);
data=arrayfun(f,xgroup);
about funtion 'fun1', now shall I return two result into the 'data' for one element of xgroup;
funtion re=fun1(x)
....
out1=x^2;
out2=x^3;
re=[out1 out2];
end
When I do like above, Matlab cant accept it; so is there some method to return several results by one 'var'?

Best Answer

Solution 1: You actually don't need arrayfun at all.
The simplest, neatest and fastest MATLAB code uses code vectorization, very simply like this:
>> x = [1,2,3];
>> y = x.^2
y =
1 4 9
>> z = x.^3
z =
1 8 27
Solution 2: Return TWO Outputs
function [sq,cu] = myFunTwo(x) % two outputs
sq = x^2;
cu = x^3;
end
and call it:
>> [outSqr,outCub] = arrayfun(@myFunTwo,[1,2,3])
outSqr =
1 4 9
outCub =
1 8 27
Solution 3: Use arrayfun's "UniformOutput" Option
function out = myFunOne(x) % one output
sq = x^2;
cu = x^3;
out = [sq,cu];
end
and call it:
>> outCell = arrayfun(@myFunOne,[1,2,3],'UniformOutput',false);
>> outCell{:}
ans =
1 1
ans =
4 8
ans =
9 27
The first solution is by far the simplest and fastest.