How can I check if the columns of my matrix have value in common?
13 views (last 30 days)
Show older comments
HelpAStudent
on 26 Sep 2021
Hi, I have a basic problem.
I have a matrix 7x21 double and I want to compare each column with the others. I want to understand if a value in the first column is repeated in the following 20 columns. Either a value from the sixth column in all five first or subsequent columns.
0 Comments
Accepted Answer
Walter Roberson
on 26 Sep 2021
I am not certain what you are asking
Either a value from the sixth column in all five first or subsequent columns.
M = randi(2, 10, 8)
sum(M(:,6) == M(:,1:5), 2) == 5
6 Comments
Walter Roberson
on 26 Sep 2021
When you ask "which" you might be asking what the location is, or you might be asking what the value is. My code returns 0 for locations that do not match and 1 for ones that match, so it answers the question about location.
any(matches, 2)
is 1 for rows that match.
to_compare(any(matches, 2))
will tell you the values but not the location
More Answers (2)
yanqi liu
on 26 Sep 2021
sir,may be use the follow code
clc
close all
clear all
% init matrix
M = randi([1 100], 10, 8)
% choose one column
use = 4;
% find value
Mu = M(:, use)
M2 = M;
M2(:, use) = NaN;
% the different range
th = 0;
for i = 1 : length(Mu)
mi = Mu(i);
di = abs(M2 - mi);
[r, c] = find(di <= th);
fprintf('\n\nthe %d data of column %d is %d\n', i, use, mi);
if length(r) < 1
fprintf('\n can not find other column has this value!');
end
for j = 1 : length(r)
fprintf('\nM(%d,%d)=%d', r(j), c(j), M(r(j), c(j)));
end
end
fprintf('\n');
2 Comments
yanqi liu
on 27 Sep 2021
clc
close all
clear all
% init matrix
M = randi([1 100], 10, 8)
% choose one column
use = 4;
% find value
Mu = M(:, use)
M2 = M;
M2(:, use) = NaN;
% the different range
th = 0;
for i = 1 : length(Mu)
mi = Mu(i);
di = abs(M2 - mi);
[r, c] = find(di <= th);
fprintf('\n\n the %d data of column %d is %d\n', i, use, mi);
if length(r) < 1
fprintf('\n can not find other column has this value!');
continue;
else
fprintf('\n I find the same value in here! Please view the follow %d data for detail!', length(r));
end
for j = 1 : length(r)
fprintf('\n M(%d,%d)=%d', r(j), c(j), M(r(j), c(j)));
end
end
fprintf('\n');
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!