copy row or column with condition?
4 次查看(过去 30 天)
显示 更早的评论
if i have (n,m) matrix A like
A = [ 0 0 1 0
1 0 1 1
0 0 0 0
0 0 1 0 ]
then i want a function to do this
- if the number of ones in the row > m/2 then copy it and put it in zeros matrix in same position
- if the number of ones in the column > n/2 then copy it and put it in RANDOM matrix in same position
expected result is
S = [ 1 1 1 0
1 0 1 1
0 1 0 1
1 0 1 1 ]
WHERE the second row and last column are the same in A
1 个评论
Jan
2016-4-16
How can you "expect" an output, when the data is based on any random values?
The wanted operation consists of two steps and in each step a matrix is created. But then I'd expect 2 outputs. But you mention one output only, so I think you forgot to explain, how the two steps are connected.
回答(2 个)
Andrei Bobrov
2016-4-16
[m,n]=size(A);
S = randi([0 1],[m,n]);
t = bsxfun(@or,sum(A,2) > n/2,sum(A,1) > m/2);
S(t) = A(t);
0 个评论
Image Analyst
2016-4-16
How did you get the first case (copying to a zeros matrix)? The only row of S satisfying #1's > 4/2 is row #2 where there are 3 1's. And you copied over that row, but where did all the 1's in the other rows come from? Why did you change them from zeros to ones in rows 1, 3, and 4???
Here is how I would solve your first case:
A = [ 0 0 1 0
1 0 1 1
0 0 0 0
0 0 1 0 ]
[rows, columns] = size(A);
% Sum up the number of ones in each row of A
rowSums = sum(A == 1, 2)
% Initialize an array called S of all zeros the same size as A
S = zeros(size(A))
% Determine which rows we need to copy from A to S
rowsToCopy = rowSums > columns/2
% Do the actual copying:
S(rowsToCopy, :) = A(rowsToCopy, :)
Also, for the second case, can you give the expected output for the column algorithm where you copy the 1's to a random matrix? You forgot to give that result. Your S is certainly not random. All I know is you must start with
S = rand(size(A))
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!