output iteration results from a loop in Matlab
我正在尝试使用for循环在单元格数组中进行一些计算,但最后只显示最后一个循环的结果。我希望Matlab显示所有循环的结果。这里是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | slope=[]; time=[]; position= []; for p=1:max(L) % max L gives the number of result{n}. so if max(L)=6 we have from result{1} to result{6} and therefore 6 final values that i want to get% a=result{n}(:,1); b=result{n}(:,2); end B = [ones(length(a),1) a] \\ b % this is to obtain the slope and intercept of a lin. regresion slope = B(2) time = result{n}(end,1)-result{n}(1:1) position = (slope.*result{n}(end,1)+intercept)-(slope.*result{n}(1:1)+intercept) |
目前在输出中得到的是:
斜率=
1 | 4.4089 |
时间=
1 | 0.5794 |
位置=
1 | 2.5546 |
此结果正确。但是,这些值是通过result {6}获得的值,我需要此值之前的值。
非常感谢您的帮助!
预先感谢!
最简单的方法是删除";"用于您要打印到命令窗口的行。这将显示您需要的所有循环值。
1 2 3 4 |
您正在弄乱索引……很难理解您对代码所做的事情,但是可能是这样的(伪代码,因为您给出的代码没有声明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | slope=zeros(1,max(L)); % Pre allocate zeros, one index for each interation time=zeros(1,max(L)); position=zeros(1,max(L)); a=zeros(1,max(L)); b=zeros(1,max(L)); for p=1:max(L) % max L gives the number of result{n}. so if max(L)=6 we have from result{1} to result{6} and therefore 6 final values that i want to get% a(p)=result{p}(:,1); b(p)=result{p}(:,2); B = [ones(length(a( p ),1) a( p )] \\ b( p) % this is to obtain the slope and intercept of a lin. regresion slope( p) = B(2) time( p) = result{p}(end,1)-result{p}(1:1) position( p) = (slope( p ).*result{p}(end,1)+intercept)-(slope ( p) .*result{p}(1)+intercept) end |
position(6)将获得您的值,position(5)将获得先前的值。
您可以在循环内进行所有计算,并且不要用";"进行阻塞反而。如果从循环中出来后得到结果,则只会得到最后一个结果。