필터 지우기
필터 지우기

pointwise multiplication of sparse matrix with full array

조회 수: 3 (최근 30일)
Sandra Martinez
Sandra Martinez 2022년 12월 12일
댓글: Sandra Martinez 2022년 12월 13일
How can I do this operation?
A=sparse([1 0;0 0]);
B=rand(2,2,2,2);
C=A.*B;
Error using .*
N-D sparse output arrays are not supported.
the only way is converting B into a sparse array with this function?
remark: A is sparse but B is not.

채택된 답변

Torsten
Torsten 2022년 12월 12일
편집: Torsten 2022년 12월 12일
rand(2,2,2,2) generates a (2x2x2x2) array for B. You cannot multiply A with such a B elementwise because the array sizes don't match.
A=sparse([1 0;0 0]);
B=rand(2,2);
C=A.*B
C =
(1,1) 0.6805
Or what do you expect as result for B being (2x2x2x2) ?
  댓글 수: 2
Torsten
Torsten 2022년 12월 12일
@Sandra Martinez comment moved here:
Yes, I know. But if A is a full matrix this is possible ( in that case matlab makes the pointwisemultiplicación of B(: , : , i,j) with A, for each i,j) The problem here is with a sparse matix and pointwise multiplication
Torsten
Torsten 2022년 12월 12일
편집: Torsten 2022년 12월 12일
Maybe
?
But I wouldn't go this way of artificial data structures further.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sandra Martinez
Sandra Martinez 2022년 12월 13일
Yes, this works now
M=rand(2,2,2,2);
N=[1 0;0 0];
A=ndSparse(M);%You need to download this function
Unrecognized function or variable 'ndSparse'.
B=sparse(N);
C=A.*B;
But, what do you mean by "artificial data structure"? In fact, I measure times and making pontiwise multiplication with full arrays takes less time (a factor 7).
n=50;
for i=1:20;
M=rand(n,n,n,n);
N=zeros(n,n);
N(1,1)=2;
tic
L=M.*N;%pointwise multiplication with full arrays
t1=toc;
tt(i)=t1;
A=ndSparse(M);%You need to download this function
B=sparse(N);
tic
C=A.*B;%pointwise multiplication using
sparse arrays
t2=toc;
tt2(i)=t2;
end
%%
% mean(tt)
% 0.0045
%mean(tt2)
% 0.0350
But if both are matices the time is the other way
for i=1:20;
M1=rand(n,n);
N1=zeros(n,n);
N(1,1)=2;
tic
L1=M1.*N1;
t3=toc;
tt3(i)=t3;
A1=ndSparse(M1);
B1=sparse(N1);
tic
C1=A1.*B1;
t4=toc;
tt4(i)=t4;
end
mean(tt4)/mean(tt3)
% 5.8859 doing pointwise multiplication using sprse matrices it is almost 6
% times faster.
Is there an explanation for that?
  댓글 수: 2
Torsten
Torsten 2022년 12월 13일
The author of ndSparse (Matt J) is active in this forum.
Maybe you should open a new question where ndSparse is part of the title and ask him directly.
Sandra Martinez
Sandra Martinez 2022년 12월 13일
OK. I will do that. Thank you very mucho for your answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Language Fundamentals에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by