Home > other >  delete rows in matrix in conditions in matlab
delete rows in matrix in conditions in matlab

Time:12-29

My program creates a matrix whose cell values ​​in multiple rows are the same in the corresponding column. I want to delete some rows that have 0 more than one. To clarify, my matrix has the following form,

A=[ 1 1 1 0 0 1 1 1; 1 0 0 1 1 1 1 1 1; 1 1 1 1 1 1 1 0; 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 ]

and I want to delete all the columns that are in the first, second and fifth rows because the number 0 is 2 or more left in the matrix of rows that are in the third and fourth rows because they have 0 one in each row. The result should be the following matrix:

A=[ 1 1 1 1 1 1 1 1 0; 1 1 1 1 0 1 1 1 ]

CodePudding user response:

i write this code for your algorithm than work correctly:

% Input Matrix
A = [1 1 1 0 0 1 1 1;1 0 0 1 1  1 1 1; 1 1 1 1 1 1 1 0;1 1 1 1 0 1 1 1;1 1 0 1 0 0 1 1 ];

% find number of rows and cols
[num_rows, num_cols] = size(A);

% Itrate on each row and find rows that have less than 2 zeros
selected_rows = [];
idx = 1;
for i=1:num_rows
    num_zero = sum(A(i, 1:end) == 0);
    if num_zero < 2
        selected_rows(idx) = i;
        idx = idx 1;
    end
end

% return result matrix
result = [];
for i=1:length(selected_rows)
    result = [result; A(selected_rows(i), 1:end)];
end

disp(result)

CodePudding user response:

  1. Create a (column) vector with the count of the number of zeros in each row.
  2. Convert the vector to a logical array that contains 0 (false) if the number of zeros is greater than 1.
  3. Use logical indexing to create a new matrix containing only the rows with 0 or 1 zero values.

Alternatively:

  1. Convert the vector to a logical array that contains 1 (true) if the number of zeros is greater than 1.
  2. Use logical indexing to delete rows containing more than 1 zero value from the original matrix.
  • Related