将循环变量存储为向量

时间:2015-03-18 02:44:24

标签: matlab for-loop vector

我有一些值,我想存储为矢量或数组,以便我可以将其输出到表中。

这是我到目前为止的代码:

xCenter = 50;
yCenter = 50;
theta1 = 0 : 0.314159 : 2*pi;
radius = 25;
x1 = radius * cos(theta1) + xCenter;
y1 = radius * sin(theta1) + yCenter;
plot(x1, y1);
axis square;
xlim([0 100]);
ylim([0 100]);
grid on;

r=25; %distance between centerline of drive axle and the ICR
l=2; %distance between wheels on drive axle
xcenter=50
ycenter=50

for theta1=0:pi/10:2*pi
    theta1 
    thetadot=theta1/1 %thetadot is the angular velocity so theta gets divided by 1 second.
    x1=r*cos(theta1)+xcenter
    xdot=x1/20 %xdot is the velocity, so the distance x gets divided by 20 seconds

    y1=r*sin(theta1)+ycenter
    ydot=y1/20 %ydot is the velocity, so the distance y gets divided by 20 seconds

    Rtheta=[cos(theta1) sin(theta1) 0; -sin(theta1) cos(theta1) 0; 0 0 1]

    XIi=[x1 y1 theta1]

    %Velocity in the global frame
    XIidot=[xdot ydot thetadot]

    %Velocity in the local frame
    XIrdot=XIidot*Rtheta
end

现在,我不确定如何将来自theta1,XIidot和XIrdot的值存储到向量中,以便将它们输出到表中。我已经使用了从theta1中的步骤定义的for循环,那么我如何将它们存储到向量中呢?

我希望将表格格式化,以便theta1,XIidot和XIrdot各自都是它们自己的列。像这样:

         theta    XIidot    XIrdot
         _____    ______    ______

Position1    38       71        176   
Position2    43       69        163   
Position3    38       64        131   
Position4    40       67        133   
Position5    49       64        119   

我试过寻找答案,但我能找到的所有问题都与我的相似。

提前感谢您的帮助。

大卫

2 个答案:

答案 0 :(得分:0)

theta = [0:pi/10:2*pi];
XIrdot = zeros(..., length(theta));
XIrdot = zeros(..., length(theta));
for i=1:1:length(theta)
    theta1=theta(i);
   ...
   XIidot(:, i) = .....
   XIrdot(:,i) = ......
end

要么整个循环矢量化,要么像这样丑陋。

答案 1 :(得分:0)

你的物理学没有意义,所以我也要看一下。

$ x = r cos \ theta $

$ \ dot {x} = \ dot {r} cos \ theta - r sin \ theta \ dot {\ theta} $

所以你不能同时定义$ \ dot {theta} $和$ \ dot {x} $

但对于你提出的问题。

您需要做的就是将theta1从循环转换为向量。唯一需要循环的地方就是你在做旋转矩阵的时候,如果你想要考虑它,你也可以去掉它。

xCenter = 50;
yCenter = 50;
theta1 = 0 : 0.314159 : 2*pi;
radius = 25;
x1 = radius * cos(theta1) + xCenter;
y1 = radius * sin(theta1) + yCenter;
plot(x1, y1);
axis square;
xlim([0 100]);
ylim([0 100]);
grid on;

r=25; %distance between centerline of drive axle and the ICR
l=2; %distance between wheels on drive axle
xcenter=50;
ycenter=50;

theta1=reshape(0:pi/10:2*pi, [], 1);

thetadot=theta1/1; %thetadot is the angular velocity so theta gets divided by 1 second.
x1=r*cos(theta1)+xcenter;
xdot=x1/20; %xdot is the velocity, so the distance x gets divided by 20 seconds

y1=r*sin(theta1)+ycenter;
ydot=y1/20; %ydot is the velocity, so the distance y gets divided by 20 seconds



XIi=[x1, y1, theta1];

%Velocity in the global frame
XIidot=[xdot ydot thetadot];
XIrdot = zeros(size(XIidot));

%Velocity in the local frame
for i = 1:length(theta1)
    Rtheta=[cos(theta1(i)) sin(theta1(i)) 0; -sin(theta1(i)) cos(theta1(i)) 0; 0 0 1];
    XIrdot(i, :)=XIidot(i, :)*Rtheta;
end

table(theta1, XIidot, XIrdot)