How to input and operate matrices using loop?

I have 1000 matrices with names C1, C2 ...... C1000. I want to input these matrices, using loop, into my function and operate them in this way:
D1 = 0.5*sum(diag((C1)-(C2)*(inv(C2)-inv(C1))))
D2 = 0.5*sum(diag((C2)-(C3)*(inv(C3)-inv(C2))))
.
.
.
Dn = 0.5*sum(diag((Cn)-(Cn+1)*(inv(Cn+1)-inv(Cn))))
Then i want to store the values of D in a vector named Distance.
Distance=[D1,D2,....,Dn]
Can anyone help me?

댓글 수: 5

You can create arrays to store these matrices. You have a 1000x1 array called D where each row element corresponds to a certain matrix. Row m corresponds to D(m). Same thing with the C matrices. Create an array named C that is 1000x1 where each row element corresponds to a certain C, namely row element m corresponds to matrix C(m).
for i = 1:1000
D(i,1) = f(C(i,1));
end
Here f is the function you would like to use.
Umair Khan
Umair Khan 2016년 7월 3일
Yes, this works now. Thanks David
Stephen23
Stephen23 2016년 7월 4일
@Umair Khan: David Miller has given your the correct solution to this task: use arrays and indexing.
You original question was about "input and operate matrices using loop": doing this is a slow and buggy way to write code, and should be avoided (e.g. by using arrays and indexing). Read this to know why:
Umair Khan
Umair Khan 2016년 7월 7일
@Stephen Cobeldick: The solution of David works fine.
In your suggested page, i found that dynamically creation of variables is bad and we should use, for example, cell arrays. In david's solution we used cell arrays. Means its fine???
Stephen23
Stephen23 2016년 7월 7일
편집: Stephen23 2016년 7월 7일
@Umair Khan: David Miller's solution is good (it should really have been submitted as an answer).
Note that David actually uses numeric array, not a cell array as you state.

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

답변 (1개)

John
John 2016년 7월 7일

0 개 추천

Concatenate all of your matrices to create a 3D array C and index the 3rd dimension using your loop variable i.e. C(:,:,1) would index the matrix C1

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2016년 7월 1일

답변:

2016년 7월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by