Filter löschen
Filter löschen

variable inputs function and reiteration

2 Ansichten (letzte 30 Tage)
raffaele
raffaele am 12 Nov. 2014
Kommentiert: Guillaume am 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.

Akzeptierte Antwort

Guillaume
Guillaume am 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 Kommentare
raffaele
raffaele am 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 am 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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by