variable inputs function and reiteration

2 次查看(过去 30 天)
Hi everyone, Is there a way to write a function with variable input and reiterated computations? for example, I have to write this function:
function[M] = fx(a1, a2, b1, b2, c1, c2, ....)
a=f(a1,a2);
b=f(b1,b2);
c=...
...
...
M=[a b c d ...];
Where f() is a generic function that I want to apply to every couple of input, and the number of these input is variable.

采纳的回答

Guillaume
Guillaume 2014-11-12
function M = fx(varargin)
if mod(nargin, 2) == 1
error("you must supply an even number of arguments")
end
M = [varargin{1:2:end}] .* [varargin{2:2:end}];
end
  2 个评论
raffaele
raffaele 2014-11-12
Sorry, I've explained not well the problem: I don't want to multiply x1*x2, I just want to apply a generic function to all the couple x1, x2. So I wondered if there is a way to say matlab to repeat the function that I apply to the input couple. I will give you an example: a=corr(a1, a2); b=corr(b1, b2); ... ... M=[a b ...]
Guillaume
Guillaume 2014-11-12
It's still the same principle. This time you have to use a loop.
function M = fx(fn, varargin)
if mod(nargin, 2) == 1
error("you must supply an even number of arguments")
end
numpairs = numel(varargin) / 2;
M = zeros(1, numpairs);
for pair = 1:numpairs
M(pair) = fn(varargin{pair*2-1}, varargin{pair*2});
end
end
The bits between %% can be replaced by an arrayfun:
M = arrayfun(@(pair) fn(varargin{pair*2-1}, varargin{pair*2}), 1:numel(varargin)/2);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by