Clear Filters
Clear Filters

variable inputs function and reiteration

2 views (last 30 days)
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.

Accepted Answer

Guillaume
Guillaume on 12 Nov 2014
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 Comments
raffaele
raffaele on 12 Nov 2014
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 on 12 Nov 2014
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);

Sign in to comment.

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!