如何将其简化为循环? MATLAB

时间:2015-03-29 13:26:55

标签: matlab loops for-loop

编辑:我知道这个问题正在被投票,但仍然非常感谢任何帮助。

我试图将其简化为此,它可以变得更简单吗?

x(1) = 1;
y(1) = 0;
x(2) = x(1) - y(1)*10^(0)
y(2) = y(1) + x(1)*10^(0)

  for n=2:3
 x(n+1) = x(n) - y(n)*0.1
 y(n+1) = y(n) + x(n)*0.1

  end
  for n=3:8
 x(n+2) = x(n+1) - y(n+1)*0.01
 y(n+2) = y(n+1) + x(n+1)*0.01
  end
  for n=4:5
 x(n+7) = x(n+6) - y(n+6)*0.001
 y(n+7) = y(n+6) + x(n+6)*0.001    
  end
  for n=5:8
 x(n+8) = x(n+7) - y(n+7)*0.0001
 y(n+8) = y(n+7) + x(n+7)*0.0001

 end

编辑:尝试实施Beaker的建议:

x(1) = 1;
y(1) = 0;
x(2) = x(1) - y(1)*1
y(2) = y(1) + x(1)*1
a=[x, 1, 1, 0.1, 0.1, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.0001, 0.0001, 0.0001, 0.0001]
 for n=2:16
     x(n+1) = x(n) - y(n)*0.1
     y(n+1) = y(n) + x(n)*0.1
 end
 a*x(n+1)

1 个答案:

答案 0 :(得分:2)

你越走越近了。这就是我要做的事情:

x(1) = 1;
y(1) = 0;
%// x(2) and y(2) will be computed in loop
%// my a[] vector was off in the comments
a=[1, 1, 0.1, 0.1, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.001, 0.001, 0.0001, 0.0001, 0.0001, 0.0001];
for n=2:16
   x(n) = x(n-1) - y(n-1)*a(n); %// multiplier goes here...
   y(n) = y(n-1) + x(n-1)*a(n); %// and here.
end

你偷偷溜进了x(n+1) =y(n+1) =。我不知道你为什么要那样做,所以我重新写了。输出是:

x =

 Columns 1 through 8:

   1.00000   1.00000   0.90000   0.79000   0.77810   0.76612   0.75406   0.74193

 Columns 9 through 16:

   0.72972   0.71744   0.71620   0.71497   0.71484   0.71472   0.71460   0.71447

y =

 Columns 1 through 8:

   0.00000   1.00000   1.10000   1.19000   1.19790   1.20568   1.21334   1.22088

 Columns 9 through 16:

   1.22830   1.23560   1.23632   1.23703   1.23710   1.23718   1.23725   1.23732