copy row or column with condition?

3 次查看(过去 30 天)
Firas Al-Kharabsheh
评论: Jan 2016-4-16
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
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
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);

Image Analyst
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))

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by