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.5computes the sum for all rows at once, resulting in an 8x1 logical array. Using this directly in anifstatement 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 ofTn—this dimension mismatch is the main reason for your error. Instead, you should append the valid row directly to the end ofTn. - Unnecessary Duplication: You initialize
Tnwith the first row, then start your loop ati=1—this will re-add the first row toTnif 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
相关产品推荐
相关产品推荐

