Checking if columns of matrix are equal to some array
Show older comments
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?
Accepted Answer
More Answers (2)
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.
Kevin Holly
on 21 Jun 2022
Edited: Kevin Holly
on 21 Jun 2022
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.
Categories
Find more on Interpolation of 2-D Selections in 3-D Grids in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!