We usually do this in a vector way, and not element by element. However, your first attempt is almost correct for a loop-based approach. The only modification to bring is not to use t as a loop index, as it is not (and should not be) an integer greater or equal to 1.
t = 0 : 0.1 : 10*pi ;
for k = 1 : length(t)
x(k) = 6*t(k) + 3*sin(2*t(k)) ;
y(k) = 3 + 3*cos(2*t(k)) ;
end
As you can see, elements of t can now have any value. If you do this though, the size of x and y increases as the loop progresses. This isn't efficient, because each time MATLAB must resize these variables, it has to "ask" for a bigger chunk of free memory, copy the old content, update the last element, and free the previous chunk of memory, which is slow. Therefore, we usually preallocate memory for variables like x and y in this context:
t = 0 : 0.1 : 10*pi ;
x = zeros(size(t)) ;
y = zeros(size(t)) ;
for k = 1 : length(t)
x(k) = 6*t(k) + 3*sin(2*t(k)) ;
y(k) = 3 + 3*cos(2*t(k)) ;
end
This way, memory for the full/final size of x and y is reserved before the loop starts (filled with 0's), and the code in the loop is just re-defining each element of x and y without changing their size.
But as I mentioned above, we usually do this kind of operations in a vector way:
t = 0 : 0.1 : 10*pi ;
x = 6*t + 3*sin(2*t) ;
y = 3 + 3*cos(2*t) ;
If you evaluate sin(t), you will see that most MATLAB functions and operators can take vectors as inputs, and output vectors. The only thing that you have to care for is to use dotted operators to enforce element-wise operations when it is relevant. E.g.
C = A * B .. is a matrix multiplication of A by B.
C(1,1) = A(1,1)*B(1,1) + A(1,2)*B(2,1) for example.
whereas
C = A .* B .. is an element-wise multiplication of elements of A
by elements of B. C(2,2) = A(2,2)*B(2,2) for example.
Additions and subtractions don't need to be dotted, but most other operators need to be dotted for performing element-wise operations.
Best Answer