Simplifying 4 for loops into one

1 visualización (últimos 30 días)
Mihail Anghelici
Mihail Anghelici el 22 de Feb. de 2021
Comentada: Mihail Anghelici el 22 de Feb. de 2021
Hello, I have the following piece of code where "cgs, mgs, house,qr" are functions. I am trying to write the following script in a nested for loop since the whole lot is repetitive enough. My problem arises when I am trying to call a different function on different iterations (cgs, mgs,etc) ,and storing each list name in a 2d array list. Anyone know how I could make this script in one for loop ?
listCGS = nan([5 1]);
for i=1:5
m=2^i;
v = ([1:m]/m)';
A = vander(v);
[Q,R] = cgs(A)
normCGS = norm(Q'*Q-eye(size(Q'*Q)));
listCGS(i) = normCGS;
end
listMGS = nan([5 1]);
for i=1:5
m=2^i;
v = ([1:m]/m)';
A = vander(v);
[Q,R] = mgs(A);
normMGS = norm(Q'*Q-eye(size(Q'*Q)));
listMGS(i) = normMGS;
end
listHouse = nan([5 1]);
for i=1:5
m=2^i;
v = ([1:m]/m)';
A = vander(v);
[Q,R] = house(A);
normHouse = norm(Q'*Q-eye(size(Q'*Q)));
listHouse(i) = normHouse;
end
listMat = nan([5 1]);
for i=1:5
m=2^i;
v = ([1:m]/m)';
A = vander(v);
[Q,R] = qr(A);
normMat = norm(Q'*Q-eye(size(Q'*Q)));
listMat(i) = normMat;
end
Thank you very much.

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 22 de Feb. de 2021
Why not just put it all in one loop?
listCGS = nan([5 1]);
listMGS = nan([5 1]);
listHouse = nan([5 1]);
listMat = nan([5 1]);
for i=1:5
m=2^i;
v = ([1:m]/m)';
A = vander(v);
[Q,R] = cgs(A)
normCGS = norm(Q'*Q-eye(size(Q'*Q)));
listCGS(i) = normCGS;
[Q,R] = mgs(A);
normMGS = norm(Q'*Q-eye(size(Q'*Q)));
listMGS(i) = normMGS;
[Q,R] = house(A);
normHouse = norm(Q'*Q-eye(size(Q'*Q)));
listHouse(i) = normHouse;
[Q,R] = qr(A);
normMat = norm(Q'*Q-eye(size(Q'*Q)));
listMat(i) = normMat;
end
  1 comentario
Mihail Anghelici
Mihail Anghelici el 22 de Feb. de 2021
There is still quite a bit of repetition, but this is good enough. Thank you !

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by