MATLAB报错Attempted to access x(0),如何用t=0:0.01:1运行代码?
Hey, let's get that code working properly! The core issue here is simple: MATLAB array indices must start at positive integers (1, not 0). When your loop runs with t=0 as the first value, you’re trying to assign to x(0) and y(0)—which MATLAB rejects because 0 isn’t a valid index. That’s why your code worked with t=1:1:100 (all positive indices) but breaks with t=0:0.01:1.
Here are two solid solutions, with the first being the most MATLAB-idiomatic:
Solution 1: Vectorized Calculation (Recommended for Speed & Simplicity)
MATLAB is built for vector operations, so you don’t even need a loop here. Just plug the entire t vector into your formula directly—MATLAB will handle element-wise calculations automatically:
Ax=0; Ay=1.5; Bx=40; By=0; Cx=0; Cy=-1.5; t = 0:0.01:1; x = ((1-t).^2)*Ax + 2*t.*(1-t)*Bx + (t.^2)*Cx; y = ((1-t).^2)*Ay + 2*t.*(1-t)*By + (t.^2)*Cy;
Note the use of .* for element-wise multiplication—this ensures each element in the t vector is calculated correctly against the other terms. This method is way faster than loops, especially with larger datasets, and avoids index issues entirely.
Solution 2: Use a Separate Index Variable (If You Prefer Loops)
If you really want to stick with a loop, create a separate index i that starts at 1 (MATLAB’s valid starting point) to track positions in x and y:
Ax=0; Ay=1.5; Bx=40; By=0; Cx=0; Cy=-1.5; t = 0:0.01:1; % Preallocate arrays first (best practice for MATLAB loops) x = zeros(size(t)); y = zeros(size(t)); for i = 1:length(t) current_t = t(i); x(i) = ((1-current_t).^2)*Ax + 2*current_t*(1-current_t)*Bx + (current_t.^2)*Cx; y(i) = ((1-current_t).^2)*Ay + 2*current_t*(1-current_t)*By + (current_t.^2)*Cy; end
Preallocating x and y with zeros() is important here—it prevents MATLAB from resizing the arrays every iteration, which slows down loops a lot.
As a side note: Your formula looks like a quadratic Bézier curve parameterization, which is perfect for vectorized computation in MATLAB—this approach plays right to the language’s strengths.
内容的提问来源于stack exchange,提问作者Adel

