필터 지우기
필터 지우기

implicit expansion for arrayfun

조회 수: 2 (최근 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