MATLAB Answers

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

2 views (last 30 days)
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.


Rik on 20 Apr 2018

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 on 20 Apr 2018

For example, I have this piece of code

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

Sign in to comment.

Accepted Answer

David Fletcher
David Fletcher on 20 Apr 2018

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


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


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


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



Show 4 older comments
Feliciano Döring
Feliciano Döring on 20 Apr 2018

so i would use a for like

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

and make it run through it?

Sign in to comment.

More Answers (0)

Sign in to answer this question.