To write a For loop in which a variable is updated with each run.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Andrei_43214
el 1 de Oct. de 2022
Respondida: Stephen23
el 1 de Oct. de 2022
I want to write a script file that generates the Cartesian coordinates of the vertices of a regular Octadecagon (18-sided regular polygon) centered at the origin and with a radius, r = 1. The coordinates can be obtained by rotating repeatedly by the angle . This can be done by matrix multiplication of
by the coordinates of a vertex of the polygon as a column vector.The first vertex is the following:
Matrix multiplication ... until will give the coordinates of all 18 vertices. I've been trying to do this in a for loop which would ideally give me the 18 coordinates as an 18x2 array but I am still very new to coding and I'm not managing to do it. I have been trying to do this so far:
R = [cos(pi/9) -sin(pi/9); sin(pi/9) cos(pi/9)];
v_1 = [sin(pi/18); -cos(pi/18)];
A = [v_1'];
for r = 1:18
column = num2str(r);
v_column = R*v_column;
v_column+('1') = v_column';
A = [A;v_column+('1')];
end
I am unable to let Matlab know that I want to update v_column to the next integer with each run. Any help/tips would be greatly appreciated.
Basically, all I want is to make the following piece of code more efficient by using a for loop (if it can be done).
R = [cos(pi/9) -sin(pi/9); sin(pi/9) cos(pi/9)];
% For i = 1,...,18: v_i = (x_i,y_i) %
v_1 = [sin(pi/18); -cos(pi/18)];
v_2 = R*v_1;
v_3 = R*v_2;
v_4 = R*v_3;
v_5 = R*v_4;
v_6 = R*v_5;
v_7 = R*v_6;
v_8 = R*v_7;
v_9 = R*v_8;
v_10 = R*v_9;
v_11 = R*v_10;
v_12 = R*v_11;
v_13 = R*v_12;
v_14 = R*v_13;
v_15 = R*v_14;
v_16 = R*v_15;
v_17 = R*v_16;
v_18 = R*v_17;
A = [v_1';v_2';v_3';v_4';v_5';v_6';v_7';v_8';v_9';v_10';v_11';v_12';v_13';v_14';v_15';v_16';v_17';v_18']
2 comentarios
Stephen23
el 1 de Oct. de 2022
Adding the pseudo-index suffix onto the variable names is neither required, nor a good approach:
Best avoided. The simple and efficient MATLAB approach is to use arrays and indexing.
Respuesta aceptada
Stephen23
el 1 de Oct. de 2022
"I want to make this more efficient by using a for loop (if it can be done)."
Of course it can be done, you just need to avoid numbering variable names like that.
Here is a basic MATLAB approach using one matrix and indexing:
R = [cos(pi/9) -sin(pi/9); sin(pi/9) cos(pi/9)];
A = [sin(pi/18), -cos(pi/18); nan(17,2)];
for k = 2:18
A(k,:) = R * A(k-1,:).';
end
display(A)
0 comentarios
Ver también
Categorías
Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!