save data from a for loop - problems with size

조회 수: 2 (최근 30일)
N
N 2014년 2월 18일
편집: N 2014년 2월 18일
I need to make a loop with a lot of calculations. If I just perform the loop, everything is fine, I get a result. The problem is that I want the results for all datapoints and not just the last one. I tried the tricks that I found online but it doesn't work. This is the normal code:
for i= 1:202;
origin2=(LE(:,i)+ME(:,i))/2;
Y2=(FH(:,i)-origin2)/norm(FH(:,i)-origin2);
ztemp2=(FH(:,i)-ME(:,i))/norm(FH(:,i)-ME(:,i));
x2=cross(Y2,ztemp2);
X2=x2/norm(x2);
z2=cross(X2,Y2);
Z2=z2/norm(z2);
R2=[X2 Y2 Z2];
midpoint=(LM(:,i)+MM(:,i))/2;
mid=(MLP(:,i)+MMP(:,i))/2;
Y3=(mid-midpoint)/norm(mid-midpoint);
ztemp3=(LM(:,i)-MM(:,i))/norm(LM(:,i)-MM(:,i));
x3=cross(Y3,ztemp3);
X3=x3/norm(x3);
z3=cross(X3,Y3);
Z3=z3
norm(z3);
R3=[X3 Y3 Z3];
end
relor=inv(R2)*R3
In the end I get a matrix for relor, this is good, its what I want. The problem is that I want results for all timepoints (so 202 results in total) to put it in a plot. Every time I put
R2(i)=[X2 Y2 Z2];
in it it gives an error that 'In an assignment A(I) = B, the number of elements in B and I must be the same !'
I don't know how to make it work, can somebody help ? !

채택된 답변

Matt Tearle
Matt Tearle 2014년 2월 18일
This code doesn't run on its own, but by eye it looks like x2, X2, y2, etc are all 3-by-1 column vectors, so R2 and R3 are 3-by-3 matrices. If you try to do R2(i) = [...] as you mention, you're asking MATLAB to assign a 3-by-3 matrix (on the right) to a single element R2(i). That's the source of your error.
If you want to store all the R2 matrices, you'll need to store them in some higher-order data structure. You could use a cell array or a 3-D numeric array:
R2{i} = [...] % R2 will be a 1-by-202 cell array
R2(:,:,i) = [...] % R2 will be a 3-by-3-by-202 double
The question is what you'll do with the result. In either case, you won't be able to use inv outside of the loop. You may be better off calculating relor inside the loop and storing the 202 results.
As an aside, use relor = R2\R3 rather than inv. For a 3-by-3 it doesn't really matter, but inverses are numerically awful -- avoid them. [/religious crusade]
  댓글 수: 1
N
N 2014년 2월 18일
편집: N 2014년 2월 18일
Your a hero thanx immensely

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by