嵌套for循环未按需求生成多组内层循环结果求助
Hey there! Let's break down why your current code only outputs a 1×5 vector, and how to adjust it to get the 90×5 matrix you need.
What's Going Wrong?
Your current code reuses the same 5-element DeltaEta vector for every iteration of the outer loop (ii). Each time you cycle through a new eta(ii), you overwrite the values in DeltaEta(1) to DeltaEta(5)—so by the end of the loop, you only have the results from the final eta value, not all 90 of them.
Solution 1: Fix the Loop with 2D Indexing
The simplest fix is to preallocate a 2D matrix (instead of a 1D vector) and use row-column indexing to store each eta(ii)'s 5 results in its own row. Here's the adjusted code:
eta = 1e-3:1e-2:9e-1; HN = 5; % Preallocate a 90×5 matrix (numel(eta) = 90) for efficiency DeltaEta = zeros(numel(eta), HN); for ii = 1:numel(eta) for v = 1:HN % Store each result in row ii, column v DeltaEta(ii, v) = eta(ii) * 6; end end
By using DeltaEta(ii, v) instead of DeltaEta(v), you're ensuring each eta value's 5 calculations get saved to a unique row, preserving all 90 sets of results.
Solution 2: Vectorize It (Faster, More MATLAB-Idiomatic)
Since every value in a row of DeltaEta is the same (eta(ii)*6 repeated 5 times), you can skip the nested loops entirely with vectorization—this is faster and cleaner in MATLAB:
eta = 1e-3:1e-2:9e-1; HN = 5; % Convert eta to a column vector, multiply by 6, then repeat across 5 columns DeltaEta = repmat(eta' * 6, 1, HN); % Or use implicit broadcasting (MATLAB R2016b+) for even more brevity: DeltaEta = (eta' * 6) .* ones(numel(eta), HN);
This works because eta' turns your 1×90 vector into a 90×1 column vector. Multiplying by 6 keeps it as 90×1, then repmat or broadcasting expands it to 90×5 by repeating the column 5 times.
Key Takeaway
The core issue was overwriting the same 1D vector instead of using a 2D structure to store all your results. Either adjusting the loop indexing or using vectorization will get you the 90×5 matrix you need.
内容的提问来源于stack exchange,提问作者Zeeshan ahmad Khan

