Check if sub-block in matrix meets a condition?

2 ビュー (過去 30 日間)
Andrew Poissant
Andrew Poissant 2018 年 9 月 14 日
編集済み: Adam Danz 2018 年 9 月 14 日
I have a 7x10 matrix of integer values (see attached .mat file). I want to check if a block inside the matrix (lets say 2x2) meets a condition. For example: lets say I want to see if any 2x2 block in the attached matrix all have values of 2. If there is such a 2x2 block within the matrix then return a value of 1 (true), if not return value of 0 (false). In the matrix attached, there is a 2x2 block of 2s so the output of what I am looking for in this example would be 1 (true). I would also like to generalize this for any size block.

採用された回答

Adam Danz
Adam Danz 2018 年 9 月 14 日
編集済み: Adam Danz 2018 年 9 月 14 日
Here's a solution that involves a loop but it's very fast. This searches for a submatrix key within a larger matrix main. Let's say key is 2x2; it will loop through all neighboring columns of main searching for key within each pair of neighboring columns. This works no matter what size key is as long as it has less columns than main. The variable isInMain will be a logical indicating whether key is in main.
It also uses strfind() which strangely operates on doubles.
Example that results in 'true'
main = randi(10, [7,10]);
key = main([3,4],[4,5]);
Example that results in 'false'
main = randi(10, [7,10]);
key = [40, 50; 11 9];
The code
isInMain = false;
finished = false;
colIdx = 0;
searchFor = true(1, size(key,1));
while ~isInMain && ~finished
colIdx = colIdx + 1;
currColumns = colIdx : colIdx + size(key,2) - 1;
ismem = ismember(main(:,currColumns), key, 'rows');
isInMain = ~isempty(strfind(ismem', searchFor));
finished = max(currColumns)+1 > size(main, 2);
end

その他の回答 (1 件)

Andrew Poissant
Andrew Poissant 2018 年 9 月 14 日
編集済み: Andrew Poissant 2018 年 9 月 14 日
Figured out the answer. I can create a 2x2 matrix of 2s and use matlab's intersect function to check if this block is present in the matrix.
[Edit] Did not work. Thought intersect could find if the 2x2 matrix is comprised in the 7x10 matrix but it can only compare individual values.
  2 件のコメント
Adam Danz
Adam Danz 2018 年 9 月 14 日
How are you using the outputs of intersect() to determine if your submatrix is within the main matrix?
Andrew Poissant
Andrew Poissant 2018 年 9 月 14 日
yeah sorry I need to undo this. Spoke too soon. I though I could use intersect to see if the 2x2 matrix is comprised in the 7x10 matrix but it only compares individual values of the 2x2 matrix. Back to square 1!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by