How do i make different matrices run through the same code?

I have a program that runs a matrix through it. Now i want another matrix to run through it in a loop so that the first one runs, gives me the output and the other one runs and gives me the output. I use operations of this first matrix that i called 'D' (like sqrt(D(1,:)) so i don't know if the other matrixes that i run through the program have to be called 'D' also or how i would do it.

2 件のコメント

Rik
Rik 2018 年 4 月 20 日

That depends. Terminology is important here: is your program a script or a function? Can you provide a MWE?

Feliciano Döring
Feliciano Döring 2018 年 4 月 20 日
編集済み: Feliciano Döring 2018 年 4 月 20 日

For example, I have this piece of code

m0=[0;0;0;0];
dn = sqrt((D(1,:)-m0(2)).^2+(D(2,:)-m0(3)).^2+(D(3,:)-m0(4)).^2);

in which 'D' is a 4x4 matrix. I would normally run the program through this line of code and get 'dn', now i want to run another matrix through the same code. they all are simple operations with the matrix

サインインしてコメントする。

 採用された回答

David Fletcher
David Fletcher 2018 年 4 月 20 日

0 投票

If your 2D matrices are of the same dimension they can be combined into a single 3D matrix:

D(:,:,1)=matrixA
D(:,:,2)=matrixB
D(:,:,3)=matrixC

Each matrix can be returned in the loop by indexing the third dimension

    D(:,:,1)
    D(:,:,2)
    D(:,:,3)

If the matrices are of differing dimensions, they can be combined into a cell array

D={matrixA,matrixB,matrixC}

again each matrix can be obtained by indexing the cell array:

D{1}
D{2}
D{3}
...

7 件のコメント

Feliciano Döring
Feliciano Döring 2018 年 4 月 20 日
And how would the array look like for n-matrices?
David Fletcher
David Fletcher 2018 年 4 月 20 日
D(:,:,1) .... D(:,:,n)
or do you mean n dimensional, rather than the 2D matrices in your example?
Feliciano Döring
Feliciano Döring 2018 年 4 月 20 日
My matrices are of different dimensions so i would have to combine them into the cell array, how would the array look like for n-matrices? And how would i run the program for each matrix?
David Fletcher
David Fletcher 2018 年 4 月 20 日
D{1} .. D{n}
Typically, you'd use the loop variable to index each matrix out of the cell array D{loopCounter}. Once you had removed each matrix from the cell array, you'd process them in the same way as you do at the moment.
Feliciano Döring
Feliciano Döring 2018 年 4 月 20 日
編集済み: Feliciano Döring 2018 年 4 月 20 日

so i would use a for like

for D=D{1}:D{n}

and make it run through it?

David Fletcher
David Fletcher 2018 年 4 月 20 日
for iter=1:n
originalMatrix=D{iter}
...
Feliciano Döring
Feliciano Döring 2018 年 4 月 23 日
Oh ok, thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by