How to tell an multi-output anonymous function to vectorize its output components which are constant

조회 수: 1 (최근 30일)
Hello friends,
I have an apparently simple but very annoying problem. Consider the function handle
f=@(x,y) [x+y;2;x*y;x^2-1;3];
When I want to calculate the expression f([1 2],3) then matlab gives an error message ('mismatch between dimensions'). Of course, I can easily fix this problem by re-defining the above function handle as
f=@(x,y) [x+y;2+x-x;x*y;x^2-1;3+x-x];
However, the problem is that my anonymous function is defined whithin a for-loop where I cannot mannually add x-x to the constants plus that
I do not know beforehand which outputs are constant and which are not. The natural way to fix this problem seems to be to update f like
f=@(x,y) f(x,y)+[0;x-x;0;0;x-x];
But, this trick does not work, unfortunately.
It is greatly appreciated if anybody has an idea how to fix this really annoying problem.
Thanks in advance
Babak Shojaei Arani

채택된 답변

Matt J
Matt J 2021년 10월 16일
편집: Matt J 2021년 10월 16일
One way,
f=@(x,y) completeRows({x+y;2;x*y;x.^2-1;3});
f([1 2],3)
ans = 5×2
4 5 2 2 3 6 0 3 3 3
function out=completeRows(C)
n=max(cellfun('length',C));
for i=1:numel(C)
if isscalar(C{i}), C{i}=repelem(C{i},1,n); end
end
out=cell2mat(C);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by