Detecting Entire Column has the same integer value
13 次查看(过去 30 天)
显示 更早的评论
Hello, I need to determine whether the entire row has the same integer value. For example;
A=[1 1;
1 0.5;
1 0.5]; The first column is all ones. Therefore, I need ans = [1 0]
However,
A=[0.5 -1
0.5 0
0.5 1]; The first column is all 0.5. I need ans = [0 0]
4 个评论
采纳的回答
Stijn Haenen
2019-11-26
Try this:
if a(:,1)==a(1,1)&mod(a(1,1),1)==0
Ans=[1 0];
else
Ans=[0 0];
end
2 个评论
Adam Danz
2019-11-26
编辑:Adam Danz
2019-11-30
This solution only analyzes the first column which would produce the following result which indicates that col 2 does not contain duplicate integers, but it does.
a=[1 1;
1 2;
1 2];
Ans = [1,0]
See my answer for a simpler and cleaner solution that generalizes to any number of columns and considers all columns.
更多回答(2 个)
Image Analyst
2019-11-26
Here's another way that works, though probably not the most compact
A=[1 1;
1 0.5;
1 0.5] % The first column is all ones. Therefore, I need ans = [1 0]
% Set non-integers to nan
mask = A == int32(A)
[rows, columns] =size(A);
output = zeros(1, columns); % Preallocate output.
for col = 1 : columns
% Set output to 1 if all of the values equal the first value.
if all(mask(:, col))
output(col) = all(A(:, col) == A(1, col));
end
end
output % Echo to command window.
A=[0.5 -1
0.5 0
0.5 1] % The first column is all 0.5. I need ans = [0 0]
% Set non-integers to nan
mask = A == int32(A)
[rows, columns] =size(A);
output = zeros(1, columns); % Preallocate output.
for col = 1 : columns
% Set output to 1 if all of the values equal the first value.
if all(mask(:, col))
output(col) = all(A(:, col) == A(1, col));
end
end
output % Echo to command window.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!