Two different size matrices multiply the overlapped element
4 次查看(过去 30 天)
显示 更早的评论
I want to multiply two matrices by using .* but the two matrics aren't the same size.
I will first align one element for two matrics, then I want the elements which are overlapped can be multiply.
What I have tried is put two matrics on a 2-D coordinate, and I can input a location which indicate two different element of two matrics.
Then find the bounder on coordinate and cut the overlap part of the two matrics and multipy together.
But the method what I tried may use lot of loops to look for the alignment element and bounder.
I am wondering whether there is a better way to solve this question ( it is not necessary to put the matrics on coordinate).
![未命名2.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/253796/%E6%9C%AA%E5%91%BD%E5%90%8D2.png)
0 个评论
回答(1 个)
Max Murphy
2019-12-10
编辑:Max Murphy
2019-12-10
Cool question. Maybe there is a better way to do it with built-in Matlab features, interested to see others approach.
Strategy
We need a way to determine the size of the overlapped region. Once we know the size of the overlapped region, we can use indexing relative to the marked point to retrieve a vector of indices giving us our two matrices for element-wise multiplication.
Algorithm
% Generate test data
A = magic(5);
B = repmat(magic(3),1,2);
% Pick a point of overlap
% Let the first column denote row index and second denote column index
% Note I will use cell arrays for indexing here,
% since you can supply multiple args to subsref that way.
iA = {2,3}; % A(iA{:}) == 7
iB = {3,4}; % B(iB{:}) == 4
dA = size(A); % [5 5]
dB = size(B); % [3 6]
%% Find inner box size
% Size of inner box is the minimum from the "right" wall
% to the co-registered point. Must also add the smaller
% of the two indexing values to account for the "left".
xDim = min(dB(2)-iB{2},dA(2)-iA{2}) + min(iB{2},iA{2}); % 3
% Same strategy for rows except with "bottom" and "top"
yDim = min(dB(1)-iB{1},dA(1)-iA{1}) + min(iB{1},iA{1}); % 4
%% Find indexing
vec = {1:yDim,1:xDim}; % Base indexing
% a,b will be "subset of A, subset of B"
% The "base indexing" will be offset
% according to some index. We will never go
% out of bounds adding to it because we have
% already computed the bounded dimension.
vec_a = {vec{1} + max(dA(1)-dB(1),0), ...
vec{2} + max(dA(2)-dB(2),0)};
vec_b = {vec{1} + max(dB(1)-dA(1),0), ...
vec{2} + max(dB(2)-dA(2),0)};
a = A(vec_a{:});
b = B(vec_b{:});
Interested to see what others come up with!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!