【问题标题】:delete rows in matrix in conditions in matlab在matlab的条件下删除矩阵中的行
【发布时间】:2022-01-26 03:40:31
【问题描述】:

我的程序创建了一个矩阵,其多行中的单元格值在对应的列中是相同的。我想删除一些 0 多于 1 的行。为了澄清,我的矩阵有以下形式,

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 ]

我想删除第一行、第二行和第五行中的所有列,因为数字 0 是 2 或更多留在第三和第四行的行矩阵中,因为它们在每行中有 0 个。 结果应该是以下矩阵:

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

【问题讨论】:

  • 您的输入矩阵在每一行中有不同数量的值,它不是矩阵,如果我尝试运行该行 MATLAB 代码会产生错误。然后你说你想删除列,但你想要的输出比输入的行少。我很困惑,完全不明白你想要完成什么。

标签: matlab conditional-statements rows


【解决方案1】:

我为您的算法编写此代码而不是正常工作:

% 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2018-10-04
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多