How to add the strings in three for loops

1 visualización (últimos 30 días)
Mahmuda Ishrat Malek
Mahmuda Ishrat Malek el 5 de Sept. de 2018
Comentada: Mahmuda Ishrat Malek el 14 de Sept. de 2018
what I want is to add 9terms(all k & m) for each i(1:3). h_1, h_2, h_3 each will have 9 additive terms. Example, h_1= h_1_1_1*a_1*b_1+ h_1_1_2*a_1*b_2+.......+h_1_3_3*a_3*b_3.
Thanks in advance.
ht=cell(3);
for i=1:3
for k=1:3
for m=1:3
code2=['h_',num2str(i),'=h_',num2str(i),'_',num2str(k),'_',num2str(m),'*a_',num2str(k),'*b_',num2str(m)];
ht{i}=strcat(ht,'+',code2)
eval(ht(i));
end
end
disp(ht(i));
end
  1 comentario
Stephen23
Stephen23 el 11 de Sept. de 2018
Indexing would be much simpler and much more efficient.
The MATLAB documentation specifically warns against going exactly what you are trying to do: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Magically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug:

Iniciar sesión para comentar.

Respuesta aceptada

Naman Chaturvedi
Naman Chaturvedi el 11 de Sept. de 2018
Correct code:
ht=cell(3,1);
for i=1:3
for k=1:3
for m=1:3
if (k*m==1)
code2=['h_',num2str(i),'=h_',num2str(i),'_',num2str(k),'_',num2str(m),'*a_',num2str(k),'*b_',num2str(m)];
ht{i}=[ht{i},code2];
else
code2=['h_',num2str(i),'_',num2str(k),'_',num2str(m),'*a_',num2str(k),'*b_',num2str(m)];
ht{i}=[ht{i},'+',code2];
end
end
end
disp(ht(i));
end
  3 comentarios
Stephen23
Stephen23 el 13 de Sept. de 2018
Editada: Stephen23 el 14 de Sept. de 2018
"...but I ended up with a lot more complex code"
That is because your approach is very complex. Indexing would be much simpler, and much more efficient.
Mahmuda Ishrat Malek
Mahmuda Ishrat Malek el 14 de Sept. de 2018
Can you give a short example on how I can do this sort of thing with indexing?

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