【问题标题】:Iterating through a matrix using a smaller matrix使用较小的矩阵迭代矩阵
【发布时间】:2019-02-13 09:30:20
【问题描述】:

我已经为此苦苦挣扎了一段时间。例如,我有一个小矩阵 s 和一个更大的矩阵 B,如下所示。

B =
     0     0     0     0     0     0     1     1
     1     1     0     0     1     0     1     1
     1     1     0     1     0     0     1     1
     1     1     1     0     0     0     1     0
     0     0     1     1     1     0     0     1
     0     0     0     1     1     1     1     1
     1     1     1     0     0     0     1     0
     0     1     1     0     1     1     0     0

s =
     1     1
     1     1

我想要做的是用s 遍历B 并比较这些值。如果s 中的所有值都等于B 中的值(B 的一小部分),则答案为 1,否则为 0。

1's0's 也将被放置在一个矩阵中。

这是我到目前为止所做的,但不幸的是,它不会逐步迭代,也不会创建矩阵。

s = ones(2,2)

B = randi([0 1],8,8)

f = zeros(size(B))

[M,N]=size(B);   % the larger array
[m,n]=size(s);   % and the smaller...

for i=1:M/m-(m-1)
  for j=1:N/n-(n-1)
    if all(s==B(i:i+m-1,j:j+n-1))
      disp("1")
    else
        disp("0")
    end
  end
end

任何帮助将不胜感激!

【问题讨论】:

  • 您没有得到足够的步数,因为您要除以较小数组的大小,这是不正确的。 (计算顶行和最左列应该有多少步,看看这些应该是什么。)此外,您永远不会为输出矩阵f 分配任何值。你真的需要使用循环吗?这将是使用conv2 的一行。

标签: matlab matrix


【解决方案1】:

以下代码适用于您提供的示例,我没有在其他任何东西上对其进行测试,如果较小矩阵的维度不是较大矩阵的维度的因素,它将不起作用,但您没有t 在您的描述中表明它需要这样做。

B =[0     0     0     0     0     0     1     1
 1     1     0     0     1     0     1     1
 1     1     0     1     0     0     1     1
 1     1     1     0     0     0     1     0
 0     0     1     1     1     0     0     1
 0     0     0     1     1     1     1     1
 1     1     1     0     0     0     1     0
 0     1     1     0     1     1     0     0];

S =[1     1
 1     1];

%check if array meets size requirements
numRowB = size(B,1);
numRowS = size(S,1);
numColB = size(B,2);
numColS = size(S,2);

%get loop multiples
incRows = numRowB/numRowS;
incCols = numColB/numColS;

%create output array
result = zeros(incRows, incCols);

%create rows and colums indices
rowsPull = 1:numRowS:numRowB;
colsPull = 1:numColS:numColB;

%iterate
for i= 1:incRows
    for j= 1:incCols
        result(i,j) = isequal(B(rowsPull(i):rowsPull(i)+numRowS-1, colsPull(j):colsPull(j)+numColS-1),S);
    end
end

%print the resulting array
disp(result)

【讨论】:

  • 谢谢凯尔,如果它们不是因素你怎么办?
  • 从您最初的帖子中并不清楚您希望如何处理不能完美平铺的矩阵集。你能澄清一下你是如何看待这种工作的吗?您可以拒绝不适合的矩阵,或者只计算两个矩阵在到达不规则边缘时重叠的部分,或者其他什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多