implicit expansion for arrayfun

4 次查看(过去 30 天)
Yi-xiao Liu
Yi-xiao Liu 2022-1-25
编辑: Matt J 2022-1-25
I want to do something similar to bsxfun, but for more than 2 arrays. For example
arrayfun(@f, A,B,C,D)
where A is a m-by-n matrix, B is a scalar, C is a m-by-1 vector, D is a 1-by-n vector. Right now arrayfun would just throw an error.
I wonder if there is something that could first check whether they are compatible, and then apply repmat so that they all become m-by-n. I couldn't find anything, but hopefully someone is better at this.
Edit:
It appears that arrayfun will do this when input is a gpuArray
"B = arrayfun(FUN,A1,...,An) applies FUN to the elements of the arrays A1,...,An, so that B(i,j,...) = FUN(A1(i,j,...),...,An(i,j,...)).The function FUN must take n input arguments and return a scalar. The nonsingleton dimensions of the inputs A1,...,An must all match, or the inputs must be scalar. Any singleton dimensions or scalar inputs are virtually replicated before being input to the function FUN."
I will dig more into this.
  1 个评论
Rik
Rik 2022-1-25
I suspect you will have to write something yourself. What did you try?

请先登录,再进行评论。

回答(2 个)

Yi-xiao Liu
Yi-xiao Liu 2022-1-25
Apparently arrayfun is a build-in function and I cannot access its source code. Here is what I come up with.
[a,b,c,d]=ImplicitExpansion(nan,[1,2,3],[4;5;6],inf)
a = 3×3
NaN NaN NaN NaN NaN NaN NaN NaN NaN
b = 3×3
1 2 3 1 2 3 1 2 3
c = 3×3
4 4 4 5 5 5 6 6 6
d = 3×3
Inf Inf Inf Inf Inf Inf Inf Inf Inf
function varargout=ImplicitExpansion(Array)
arguments (Repeating)
Array {mustBeNumericOrLogical}
end
dim=cellfun(@ndims,Array);
dim(cellfun(@isvector,Array))=1;
dim(cellfun(@isscalar,Array))=0;
[~,seq]=sort(dim,'descend');
for i=2:numel(seq)
Array{seq(i)}=Array{seq(i)}+zeros(size(Array{seq(i-1)}));
end
Array{seq(1)}=Array{seq(1)}+zeros(size(Array{seq(end)}));
varargout=Array;
end
It will throw 'MATLAB:dimagree' error when size was incompatible. Also only work with 2D numerical arrays.

Matt J
Matt J 2022-1-25
编辑:Matt J 2022-1-25
A=rand(10,5); B=3; C=rand(10,1); D=rand(1,5);
args={A,B,C,D};
sz=cellfun(@size,args,'uni',0);
maxsz=max(vertcat(sz{:}));
newargs= cellfun(@(c)repmat(c, maxsz./size(c)), args,'uni',0);
[A,B,C,D]=deal(newargs{:});
whos A B C D
Name Size Bytes Class Attributes A 10x5 400 double B 10x5 400 double C 10x5 400 double D 10x5 400 double

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by