Checking if columns of matrix are equal to some array
82 ビュー (過去 30 日間)
古いコメントを表示
Hi all,
I'm really confused as to what I'm doing wrong here. I have tried to find previous answers in the forum but have come up empty.
I am trying to iterate through the columns of a matrix and to compare each column of the matrix to a template array.
My code is as follows:
% workspace already contains data matrix of shape 8 x T
template = [0 0 1 0 0 0 1 0]
for t = 1:T
test_column = data(:,t);
if isequal(test_column, template)
disp('Template is present in data.')
return
else
disp('Template is absent in data.')
return
end
end
The code outputs "Template is absent in data.", even when the data column matches the template.
I have tried transposing the template or the test_column, but neither helps. I have also tried using the == operator in place of isequal(), but I haven't found this helps either. I think that test_column and template should both be arrays (e.g. test_column is not comma separated values as far as I can tell), so am not sure why comparison is not possible.
Does anyone have any insight?
0 件のコメント
採用された回答
Voss
2022 年 6 月 21 日
編集済み: Voss
2022 年 6 月 21 日
Don't return yet, when you find that some particular column of data is not equal to template. You still need to keep checking the rest of the columns.
template = [0 0 1 0 0 0 1 0]
is_found = false;
for t = 1:T
test_column = data(:,t);
if isequal(test_column.', template)
is_found = true;
break % stop checking
end
end
if is_found
disp('Template is present in data.')
else
disp('Template is absent in data.')
end
As you have it now, the code checks the first column, prints a message, and then returns - regardless of whether that column is equal to template.
Also, you do need to transpose one or the other for isequal to work right.
0 件のコメント
その他の回答 (2 件)
Steven Lord
2022 年 6 月 21 日
Transpose the matrix and use ismember with the 'rows' option.
rng default
x = randi([0 1], 10, 3)
candidate = [1 0 1]
isItPresent = ismember(candidate, x, 'rows')
whichRowsMatch = ismember(x, candidate, 'rows')
If your candidate or x arrays contain non-integer values you may want to use ismembertol instead.
0 件のコメント
Kevin Holly
2022 年 6 月 21 日
編集済み: Kevin Holly
2022 年 6 月 21 日
T=5
data = randi([0 1],8,T)
template = [0 0 1 0 0 0 1 0]
data(:,4) = [0 0 1 0 0 0 1 0];
for t = 1:T
test_column = data(:,t);
if isequal(test_column, template')
disp(['Template is present in column ' num2str(t) ' of data.'])
else
disp(['Template is absent in column ' num2str(t) ' of data.'])
end
end
for t = 1:T
test_column = data(:,t);
if isequal(test_column, template)
disp(['Template is present in column ' num2str(t) ' of data.'])
return
else
disp(['Template is absent in column ' num2str(t) ' of data.'])
return
end
end
return stops it after column 1 is analyzed.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!