Borrar filtros
Borrar filtros

Assign matrix names using for loops in formula

1 visualización (últimos 30 días)
peterhack
peterhack el 9 de Jun. de 2016
Comentada: Stephen23 el 9 de Jun. de 2016
Hi,
I was wondering how to get my code shorter and cleaner as I am basically using the same formula.
A = zeros(1,t);
B = zeros(1,t);
C = zeros(1,t);
D = zeros(1,t);
E = zeros(1,t);
for z = 1:1:t
if z == 1
A(:,z) = v1;
B(:,z) = v2;
C(:,z) = v3;
D(:,z) = v4;
E(:,z) = v5;
else
A(:,z) = A(:,z-1)*(1+rf);
B(:,z) = B(:,z-1)*(1+rf);
C(:,z) = C(:,z-1)*(1+rf);
D(:,z) = D(:,z-1)*(1+rf);
E(:,z) = E(:,z-1)*(1+rf);
end
end
However, I am aware of better not to use eval.
But I do not get it working using an cell array like here with names = {'A' 'B' 'C' 'D' 'E'}. vx are just some values, which I coul also loop from an array.
Thanks in advance!
  1 comentario
Stephen23
Stephen23 el 9 de Jun. de 2016
You are right to avoid eval, which is almost always a bad idea, especially with trivial looped code like this, no matter how much beginners seem attracted to using it:
The solution is to use indexing. That is all. There is no magic trick, just learn to use the dimensions of ND arrays, or cell arrays, or whatever array suits your needs, and use indexing.

Iniciar sesión para comentar.

Respuesta aceptada

Jos (10584)
Jos (10584) el 9 de Jun. de 2016
Editada: Jos (10584) el 9 de Jun. de 2016
Remember: It is the contents of the variable that should be flexible, not its name!
You will be way better off using arrays (regular, structs, or cells).
ABCDE = zeros(t, 5)
ABCDE(:,1) = [v1 v2 v3 v4 v5] ;
for z = 2:1:t
ABCDE(:,z) = ABCDE(:,z-1) .* (1+rf) ; % not sure what rf is, hence the .*
end

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing 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