How to add the strings in three for loops

1 visualizzazione (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 11 Set 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:

Accedi per commentare.

Risposta accettata

Naman Chaturvedi
Naman Chaturvedi il 11 Set 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 Commenti
Stephen23
Stephen23 il 13 Set 2018
Modificato: Stephen23 il 14 Set 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 il 14 Set 2018
Can you give a short example on how I can do this sort of thing with indexing?

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by