Borrar filtros
Borrar filtros

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

4 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 27 de Sept. de 2013
Editada: Azzi Abdelmalek el 27 de Sept. de 2013
A = [1 2;3 4]
B = [5 6;7 8]
C=cell2mat(arrayfun(@(x) x-B,A,'un',0))

Más respuestas (2)

Matt J
Matt J el 27 de Sept. de 2013
Editada: Matt J el 27 de Sept. de 2013
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 el 27 de Sept. de 2013
Editada: Matt J el 27 de Sept. de 2013
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.

Categorías

Más información sobre Particle & Nuclear Physics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by