Effacer les filtres
Effacer les filtres

How to use arrayfun with a function having two vector arguments?

15 vues (au cours des 30 derniers jours)
Mr M.
Mr M. le 18 Oct 2016
Commenté : Andrei Bobrov le 18 Oct 2016
I have a function f(W,x), where W is a matrix and x is a vector. I would like to use arrayfun to calculate the f(W,x) for several x but constant/fix W. What is the syntax?

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 18 Oct 2016
Modifié(e) : Andrei Bobrov le 18 Oct 2016
fW = @(x) f(W, x);
out = cellfun(fW,{x1,x2,x3},'un',0);
  3 commentaires
Adam
Adam le 18 Oct 2016
Well, did you try doing what the error suggests?! Set 'UniformOutput' to false:
out = cellfun(fW,{x1,x2,x3}, 'UniformOutput', false);
Andrei Bobrov
Andrei Bobrov le 18 Oct 2016
OK. Corrected.

Connectez-vous pour commenter.

Plus de réponses (2)

Rani V.S
Rani V.S le 18 Oct 2016
A = arrayfun(FUN, B, C, ...) evaluates FUN using elements of arrays B,
C, ... as input arguments. The (I,J,...)th element of A is equal to
FUN(B(I,J,...), C(I,J,...), ...). B, C, ... must all have the same size.

Guillaume
Guillaume le 18 Oct 2016
%W = [.,.,.;.,.,.;.,.,.]; %matrix
%x = [.,.,.,.,.,.]; %vector
result = arrayfun(@(xelem) f(W, xelem), x); %possibly with 'UniformOutput', false, if f output is not scalar
Or if you want to be more explicit
%W = [.,.,.;.,.,.;.,.,.]; %matrix
%x = [.,.,.,.,.,.]; %vector
fW = @(x) f(W, x); %W must exists before this line. Changing W after this line will not affect fW
result = arrayfun(fW, x);
In either case you're creating a new function (with no name in the first case, fW in the second) that binds the matrix W to f and still takes x as an input. You're then using that function in arrayfun to apply it to each element of x.
  2 commentaires
Mr M.
Mr M. le 18 Oct 2016
That is OK, but I have x1 vector, x2 vector, x3 vector, ... and I want to apply fW thru arrayfun once. Is it possible?
Guillaume
Guillaume le 18 Oct 2016
Well, first you shouldn't have numbered variables x1, x2, etc. Instead you should have just one variable which is a cell array of vectors. In that case, use cellfun:
x = {x1, x2, x3}; %you really shouldn't create the xi to start with. Put their content in the cell array as you create it.
result = cellfun(@(xv) f(W, xv), x, 'UniformOutput', false);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by