필터 지우기
필터 지우기

copy row or column with condition?

조회 수: 3 (최근 30일)
Firas Al-Kharabsheh
Firas Al-Kharabsheh 2016년 4월 16일
댓글: 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