variable inputs function and reiteration

1 vue (au cours des 30 derniers jours)
raffaele
raffaele le 12 Nov 2014
Commenté : Guillaume le 12 Nov 2014
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.

Réponse acceptée

Guillaume
Guillaume le 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 commentaires
raffaele
raffaele le 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 le 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);

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by