Vectorized iterative summation of matrices
1 次查看(过去 30 天)
显示 更早的评论
Dear MATLAB community,
I want to iteratively sum over matrices and store my result. I defined a mask where every 1 value defines a position where I want to insert a matrix around it. If two inserted matrices overlap, I want to summarize the value. Doing this with a for loop is very easy but also very time consuming if I am dealing with large matrices. Therefore, I wanted to do this with a vectorized expression. However, it does not work as intended yet. Let me show you what I got:
% This defines the mask I am using for inserting the matrices. At each 1 I
% want to insert another matrix b
a=eye(10);
a(1,1)=0;
a(end,end)=0;
% define matrix b to be inserted
b = [1 2 3; 4 5 6; 7 8 9];
% define result matrix
c = zeros(10,10);
% now iteratively put the b matrix at each defined position by a and
% summarize overlapping parts
[ix,iy] = find(a==1);
c(ix-1:ix+1,iy-1:iy+1) = c(ix-1:ix+1,iy-1:iy+1) + b;
My problem is that MATLAB only inserts the matrix b at the very first pair of indices. For all other positions it does not work. As I said, for computational time reasons I wanted to find a vectorized expression instead of using loops. Does anyone have an idea how to do that?
Thank you in advance!
0 个评论
更多回答(1 个)
David Hill
2021-12-3
编辑:David Hill
2021-12-3
What is wrong with using a loop? Why do you think it is going to be slower?
a=eye(10);
a(1,1)=0;
a(end,end)=0;
b = [1 2 3; 4 5 6; 7 8 9];
d = zeros(10,10);
[ix,iy] = find(a==1);
for k=1:length(ix)
c=zeros(10,10);
c(ix(k)-1:ix(k)+1,iy(k)-1:iy(k)+1)=b;
d=d+c;
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!