How to find the find the pattern in each row of Matrix?

3 ビュー (過去 30 日間)
Kazi Alam
Kazi Alam 2021 年 6 月 10 日
編集済み: Adam Danz 2021 年 6 月 10 日
Hallo, Thanks for reading!
The array that I am working with consist of 8 column.
1 2 3 4 5 6 7 8
==========================================================
0 3.2 0 3.3 0 2 19 0
3.2 0 3.2 0 3.3 0 2 0
0 0 6.2 0 0 8 21 0
3.2 9 3.2 0 0 0 2 0
...
The goals is to find the column number which are non-zeros. For example: row1 = 2468, row2 = 1357, row3= 367 so on. With these I would like finally find out what is the most frequent pattern.
The current code is
for i=1:length(data)
k(i,:)= find(data(i,:)~=0);
end
However, my array is inconsistent how to solve this problem? Returning the following error:
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

採用された回答

Kazi Alam
Kazi Alam 2021 年 6 月 10 日
編集済み: Kazi Alam 2021 年 6 月 10 日
Already found a better option!
Here is the code.
for i=1:length(outerwall)
k(:,i)= str2double(sprintf('%d',find(outerwall(i,:)~=0)));
end
Edit:
for more info
  1 件のコメント
Adam Danz
Adam Danz 2021 年 6 月 10 日
編集済み: Adam Danz 2021 年 6 月 10 日
This solution is bad for two reasons.
  1. Is very inefficient. It converts vectors to strings, then back to a numbers, and uses a loop, all of which can be avoided.
  2. Most importantly, this method will fail if there are more than 9 columns. Example: let's say the pattern in row j is [1 3] and the pattern in row k is [13]. That produces the same output "13" even though the 2 patterns have no overlap at all. Another example: what columns are represented by '123'? [1 2 3] or [1, 23] or [123]?
dpb's answer is much more efficient, cleaner, quicker, and robust.

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

その他の回答 (1 件)

dpb
dpb 2021 年 6 月 10 日
A=[A;A(3,:)]; % make sure one row has same pattern
% the engine
B=(A~=0); % convert to logical array for pattern, independent of value
[~,ib]=ismember(B,unique(B,'rows'),'rows'); % locations of each pattern
N=histcounts(ib); % count number of each pattern located
For the above augmented, array, this returns
>> N
N =
2 1 1 1
>>
which shows the first row was duplicated; all rest were unique, only occurring once.
  2 件のコメント
Adam Danz
Adam Danz 2021 年 6 月 10 日
Good one!
Kazi Alam
Kazi Alam 2021 年 6 月 10 日
Thanks! I have found a better option. I will post it below.

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

カテゴリ

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