Filter löschen
Filter löschen

copy row or column with condition?

3 Ansichten (letzte 30 Tage)
Firas Al-Kharabsheh
Firas Al-Kharabsheh am 16 Apr. 2016
Kommentiert: Jan am 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 Kommentar
Jan
Jan am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Andrei Bobrov
Andrei Bobrov am 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 am 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))

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by