フィルターのクリア

variable inputs function and reiteration

2 ビュー (過去 30 日間)
raffaele
raffaele 2014 年 11 月 12 日
コメント済み: Guillaume 2014 年 11 月 12 日
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 Center および File ExchangeFunction Creation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by