Is there an equivalent function to the "kron(x,y)" that uses subtraction as its operation rather than multiplication?

조회 수: 1 (최근 30일)
For example,
say we have two matrices as follows:
>> A = [1 2;3 4]
A =
1 2
3 4
>> B = [5 6;7 8]
B =
5 6
7 8
>> kron(A,B)
ans =
5 6 10 12
7 8 14 16
15 18 20 24
21 24 28 32
However I want a matrix that will subtract every component of matrix A by every component of matrix B, yielding a 4x4 matrix as follows:
A - B =
[-4 -5 -3 -4;-6 -7 -5 -6;-2 -3 -1 -2;-4 -5 -3 -4]
Note that I switched the multiplication function with subtraction BY HAND here. I need to do this with two 100x100 matrices, so it wouldn't be so easy. Thanks

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 27일
편집: Azzi Abdelmalek 2013년 9월 27일
A = [1 2;3 4]
B = [5 6;7 8]
C=cell2mat(arrayfun(@(x) x-B,A,'un',0))

추가 답변 (2개)

Matt J
Matt J 2013년 9월 27일
편집: Matt J 2013년 9월 27일
Using the function below
result=tensorfun(@minus,A,B)
It is an easy modification of kron.m, but more efficient since it uses bsxfun.
function X = tensorfun(op,A,B)
%TENSORFUN
%
% X = tensorfun(operation,A,B)
%
%Generalization of KRON (as modified, e.g., by Laurent Sorber, Bruno Luong, and others)
%
%Creates matrix X consisting of blocks X_ij=bsxfun(operation,a(i,j),B).
%Note that "operation" must preserve the size of B.
[I J] = size(A);
[K L] = size(B);
if ~issparse(A) && ~issparse(B)
A = reshape(A,[1 I 1 J]);
B = reshape(B,[K 1 L 1]);
X = reshape(bsxfun(op,A,B),[I*K J*L]);
else
[ia,ja,sa] = find(A); ia=ia(:); ja=ja(:); sa=sa(:);
[ib,jb,sb] = find(B); ib=ib(:); jb=jb(:); sb=sb(:);
ix = bsxfun(op,K*(ia-1).',ib);
jx = bsxfun(op,L*(ja-1).',jb);
X = sparse(ix,jx,bsxfun(op,sb,sa.'),I*K,J*L);
end

Matt J
Matt J 2013년 9월 27일
편집: Matt J 2013년 9월 27일
I need to do this with two 100x100 matrices, so it wouldn't be so easy.
Does that mean you plan to construct a 10000x10000 matrix? I don't know exactly what you're doing, but constructing A matrix that large could be greatly inefficient. Suppose you wanted to multiply the desired matrix in your example
T=[-4 -5 -3 -4;-6 -7 -5 -6;-2 -3 -1 -2;-4 -5 -3 -4]
by a 4x1 vector c, so as to obtain y=T*c. Then it can be done equivalently, as
C=reshape(c,2,2);
result=ones(2)*C*A.'-B*C*ones(2);
y=result(:);
which involves only 2x2 matrix operations instead of the 4x4 matrix T.
For the 2x2 case, the difference is of little consequence, but when the matrices grow to be 100x100, the saving both in speed and memory is significant.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by