Call variables in for loop

8 次查看(过去 30 天)
Hi to all,
L1=4 L2=3 ... L30=12
for i=1:30 P(:,i)=sprintf(L%1d,i) - sprintf(L%1d,i+1) end
The result should be P(1)=L1-L2, P(2)=L2-L3, P(3)=L3-L4, P(4)=L4-L5 but it's not :) What should I use instead sprintf?
Thank you for you answers!!!

采纳的回答

Kevin Holst
Kevin Holst 2012-3-22
To do this like you're attempting requires the use of the eval function, but be very careful in its use. Google 'eval matlab' for more information on why. And actually, the way you've got it set up wouldn't work. Your for loop needs to run from 1:29 because there's no L31.
for i = 1:29
eval(['P(' num2str(i) ')=L' num2str(i) '-L' num2str(i+1) ';'])
end
Is there any reason why your L variables aren't in a single L vector?
  7 个评论
Kevin Holst
Kevin Holst 2012-3-22
@Oleg, I haven't tried the eval(eval(eval(... suggestion, but I did evaluate char([102 108 105 112 108 114 40 39 116 105 120 101 39 41]) in my workspace... very sneaky! ;) That's the nice way to show a problem with eval. The mean way would be to "accidentally" have someone recursively remove all of the contents of their hard drive. That'd be a bad day.
Oleg Komarov
Oleg Komarov 2012-3-22
Should have concealed it better...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by