You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab中for循环内堆叠表格行报错问题求助

Fixing Your MATLAB Stacking Code Issue

Let's walk through the problems in your code and fix them up clearly:

Key Issues in Your Original Code

  • Incorrect Condition Check: sum(T,2)<1.5 computes the sum for all rows at once, resulting in an 8x1 logical array. Using this directly in an if statement will cause errors (since MATLAB expects a single logical value here). You need to check the sum of the current row only: sum(T(i,:)) < 1.5.
  • Invalid Assignment: When you do Tn(i,:)=cat(1, Tn, T(i,:)), you're trying to assign a multi-row matrix to a single row of Tn—this dimension mismatch is the main reason for your error. Instead, you should append the valid row directly to the end of Tn.
  • Unnecessary Duplication: You initialize Tn with the first row, then start your loop at i=1—this will re-add the first row to Tn if it meets the sum condition, creating an unwanted duplicate.

Corrected Loop-Based Code

T = rand(8,3);
Tn = T(1,:);  % Start with the first row as required
for i = 2:size(T,1)  % Start from the second row to avoid duplication
    if sum(T(i,:)) < 1.5
        Tn = [Tn; T(i,:)];  % Append the valid row to Tn (simpler than cat)
    end
end

Even Better: Vectorized Approach (MATLAB-Friendly)

MATLAB works best with vectorized operations instead of loops. You can achieve the same result in one concise step without a loop:

T = rand(8,3);
% Create an index: keep first row, plus other rows where sum < 1.5
keep_rows = [true; sum(T(2:end,:), 2) < 1.5];
Tn = T(keep_rows, :);  % Extract all valid rows directly

This is faster, cleaner, and less prone to loop-related bugs.

内容的提问来源于stack exchange,提问作者user9003011

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:15:13