0

I am trying to use a for loop to make some calculations in a cell array but at the end only the results for the last loop are displayed. I would like Matlab to display the results for all loops. Here there is the code:

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)

At the moment in the output that is what i get:

slope =

4.4089

time =

0.5794

position =

2.5546

This result is correct. However, these values are the ones obtained with result{6} and i need the values previous to this one.

Any help is much appreciated !

Thanks in advance!

4

3 回答 3

1

你把索引弄得一团糟……有点难以理解你在代码上做了什么,但它可能是这样的(伪代码,因为你提供的代码没有result声明):

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) 将获得前一个值。

于 2013-08-14T19:24:15.873 回答
1

最简单的方法是删除“;” 对于要打印到命令窗口的行。这将显示您需要的所有循环值。

for p=1:max(L)
 a=result{n}(:,1)
 b=result{n}(:,2)
end
于 2013-08-15T03:51:02.200 回答
0

你能在循环内进行所有计算并且不要用“;”阻塞吗?反而。如果退出循环后得到结果,则只会得到最后一个。

于 2013-08-15T20:02:24.283 回答