conv a matrix multiple times
2 次查看(过去 30 天)
显示 更早的评论
Hello
I have a rectangular matrix and i want to convolve it to some power of that matrix times. e.g.
a = [1 1 0; 1 0 1]^5
convolve the 1st row with the 1st row 5 times and then the row with the 2nd row 5 times.
Any help!
0 个评论
采纳的回答
Bruno Luong
2019-7-26
编辑:Bruno Luong
2019-7-26
a1 = [1 1 0;
1 0 1]; % rand(2,3);
p = 5; % power
[m,n] = size(a1);
%% Method 1, straighforward double for-loops
ap = a1;
for p=2:p
temp = zeros(m,n+size(ap,2)-1);
for i=1:m
temp(i,:) = conv(a1(i,:),ap(i,:));
end
ap = temp;
end
ap
%% Method 2 single for-loop
ap = a1;
i = 0:n-1;
k = n;
A1 = reshape(a1,[m 1 n]);
for p=2:p
c = i+(1:k)';
[r,c] = ndgrid(1:m,c(:));
ap = A1.*ap;
k = n+k-1;
ap = accumarray([r(:) c(:)], ap(:), [m, k]);
end
ap
You might try to improve by using a "smart" of power raising, by using the binary decomposition of p.
2 个评论
Bruno Luong
2019-7-27
编辑:Bruno Luong
2019-7-27
Just for fun here is the code with binary decomposition of p.
It should have less computational intensive for very large p (complexity ~O(log(p)) instead of O(p)). However in my test it's slower than simple for-loop, possibly because involve more memory copying.
a1 = rand(10,3);
p = 32; % power
[m,n] = size(a1);
q = nextpow2(p+1)-1;
a2q = a1;
ap = ones(m,1);
for j = 0:q
if bitand(2^j,p)
temp = zeros(m,n+size(ap,2)-1);
for i=1:m
temp(i,:) = conv(a2q(i,:),ap(i,:));
end
ap = temp;
end
if j==q
break
end
n = 2*size(a2q,2)-1;
temp = zeros(m,n);
for i=1:m
temp(i,:) = conv(a2q(i,:),a2q(i,:));
end
a2q = temp;
end
ap
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!