Clear Filters
Clear Filters

copy row or column with condition?

3 views (last 30 days)
Firas Al-Kharabsheh
Firas Al-Kharabsheh on 16 Apr 2016
Commented: Jan on 16 Apr 2016
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 Comment
Jan
Jan on 16 Apr 2016
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.

Sign in to comment.

Answers (2)

Andrei Bobrov
Andrei Bobrov on 16 Apr 2016
[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 on 16 Apr 2016
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))

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!